Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

思路:首先应该注意标题中的关键字,输入的数组已经排序了,也就是说前面是小的数字,后面是大的数字。

自己代码:(从头开始遍历,会超时)

 vector<int> twoSum(vector<int>& numbers, int target) {
int n = numbers.size();
vector<int>index;
for(int i = ; i < n - ; i++){
for(int j = i + ; j < n; j++){
if(numbers[i] + numbers[j] == target){
index.push_back(i+);
index.push_back(j+);
}
}
}
return index;
}

优秀代码:(3ms)

 vector<int> twoSum(vector<int>& numbers, int target) {
int m = , n = numbers.size() - ;
while(m < n){
if(numbers[m] + numbers[n] < target)
m++;
else if(numbers[m] + numbers[n] > target)
n--;
else
return vector<int>{m + , n + };//这里可以直接返回vector,{}表示赋值初始化
}
}

最新文章

  1. EasyUI DateTimeBox设置默认时间的注意点
  2. 2014亚马逊在线笔试题目及解决方案(MMChess问题)
  3. 迄今最深入、最专业的Hololens评测结果,美国AR大咖艾迪&#183;奥夫曼现身说法
  4. 【USACO 1.5】SuperPrime Rib
  5. Redis 的Lua Script脚本功能
  6. table边框美化
  7. HTML前端——CSS样式
  8. java 中遇到的问题及解决方法
  9. ORA-01013:用户请求取消当前的操作
  10. IDEA和Eclipse经常使用快捷键(Win Mac)
  11. bzoj 1778 [Usaco2010 Hol]Dotp 驱逐猪猡(高斯消元)
  12. Wps的ppt里 让图片按顺序出现 就是点击一下 出现一张照片
  13. C# 之 Stream 和 byte[] 的相关转换
  14. Boost Thread学习笔记
  15. POJ 2062 HDU 1528 ZOJ 2223 Card Game Cheater
  16. 安全性测试入门:DVWA系列研究(一):Brute Force暴力破解攻击和防御
  17. SQLServer的三种Recovery Model
  18. android用OkHttp和okio包通信的坑--气死我了
  19. DRBD详细解说及配置过程记录
  20. 主流Linux发行版简介

热门文章

  1. mysql初次使用
  2. Tomcat的优化技巧
  3. JS流程控制语句 来来回回(Do...while循环) 先执行后判断 do while结构的基本原理和while结构是基本相同的,但是它保证循环体至少被执行一次。
  4. 在vue项目中使用Nprogress.js进度条
  5. 《你不知道的JavaScript》上卷——第1章
  6. Django常用组件之分页器
  7. 利用R语言制作出漂亮的交互数据可视化
  8. Java序列化接口的作用总结1
  9. wps中,怎么快速查看xls中隐藏的图片
  10. Java超简明入门学习笔记(二)