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 a,b;
for(a=0;a<numbers.size();a++)
{
for(b=numbers.size()-1;b>a;b--)
{
if(numbers[a]+numbers[b]==target)
return vector<int> {a+1,b+1};
}
}
}
改用夹逼法。
vector<int> twoSum(vector<int>& numbers, int target) {
int a=0,b=numbers.size()-1;
while(a<b)
{
if(numbers[a]+numbers[b]==target)
return vector<int> {a+1,b+1};
else if (numbers[a]+numbers[b]<target)
a++;
else
b--;
}
}

本文介绍了一种在已排序的整数数组中寻找两个数使其和等于特定目标值的有效算法。采用双指针技术,从两端向中间逼近,实现O(n)的时间复杂度。
383

被折叠的 条评论
为什么被折叠?



