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.
最开始尝试两个for循环暴力求解,预期中的TO
后来用一层for+binary search,AC,但是耗时相对太多,继续寻找好的方法
最后,使用两个idx,分别从头尾向中间移动,耗时最优
AC code:
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> rst;
int cnt = numbers.size();
int low = 0;
int high = cnt-1;
while(low<high)
{
if(numbers[low]+numbers[high] == target)
{
rst.push_back(low+1);
rst.push_back(high+1);
return rst;
}
else if(numbers[low]+numbers[high] < target)
low++;
else
high--;
}
return rst;
}
};