您的位置:首页 > 其它

[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;

代码如下:

<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>



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: