[leetcode 167] Two Sum II - Input array is sorted
2015-12-29 23:01
393 查看
Question:
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.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
分析:
设置两个指针LR,开始时候L=0,R = len-1;将num[L] + num[R] 与target相比较,如果target大,则++L,如果target小,则--R,相等,则返回LR;
代码如下:
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.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
分析:
设置两个指针LR,开始时候L=0,R = len-1;将num[L] + num[R] 与target相比较,如果target大,则++L,如果target小,则--R,相等,则返回LR;
代码如下:
<pre name="code" class="cpp"><span style="font-size:14px;">vector<int> twoSum(vector<int> &numbers, int target){ vector<int> ans; int left = 0, right = numbers.size()-1; int tmpSum = 0; while(left < right){ tmpSum = numbers[left] + numbers[right]; if (tmpSum == target){ ans.push_back(left+1); ans.push_back(right+1); return ans; } else if (tmpSum > target){ --right; }else{ ++left; } } return ans; }</span>
相关文章推荐
- HTML5 文件API(一)
- s5pv210中断体系
- Day-8 晚上。
- jinja2 字符串替换
- 浅谈innoDB,MYISAM
- python - StringIO文本缓冲
- 在Linux环境下安装部署MySQL数据库系统实例
- MongoDB 驱动以及分布式集群读取优先级设置
- 打开族,加载族
- de4dot3.14更新文件打包下载
- 2016年最值得关注的16个网页设计趋势
- Java网络连接之HttpURLConnection与HttpClient 区别及联系
- centos 安装qrcode 二维码
- VB 生成的EXE怎么更换桌面图标
- Open Source Software
- SQL 标量函数-----日期函数 day() 、month()、year()
- Linux笔记 vim
- System.Diagnostics.Process 执行.EXE
- C++编程思想学习笔记---第14章 继承和组合
- 热烈祝贺中国芯终于走在世界的前列