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
代码:#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> ret(0,0);
int left = 0;
int right = numbers.size()-1;
while(left < right)
{
int tmp = numbers[left]+numbers[right];
if(tmp == target)
{
ret[0] = left+1;
ret[1] = right+1;
return ret;
}
else if(tmp < target)
left ++;
else
right --;
}
}
};
解析:
在这里我们利用了向量的一些知识,首先我们需要创建一个新的向量ret,以便于最后的返回。
然后,在向量的两端分别定义两点为left和right。我们需要做的就是;利用这两点来遍历这个向量,直到出现他们的加和等于target的情况
所以当left小于right时,才可以正常运行,否则就说明已经遍历过所有的元素了。当出现加和等于target时,更改向量中的元素,使他们为下标index
然后返回我们创建的向量ret
否则,当加和小于target时,让left向右移动一个单位,再运算,如果大于target,则最右边的向左移动一个单位。