题面:
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
题解:开始时自然想到直接用两个循环求解,如代码1,超时,后注意到递增,所以分设两个指针,分别从前后遍历,如代码2。由于题中限制条件很多,不许太多边界判定,时间复杂度O(n),可解。
代码1:
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int>a(2);
for(int i=0;i<numbers.size();i++){
for(int j=i+1;j<numbers.size();j++){
if(numbers[i]+numbers[j]==target){
a[0]=i+1;
a[1]=j+1;
return a;
}
}
}
}
};
代码2:
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int>a(2);
int l=0;
int r=numbers.size()-1;
while(l<r){
if(numbers[l]+numbers[r]==target){
a[0]=l+1;
a[1]=r+1;
return a;
}
else if(numbers[l]+numbers[r]<target)
l++;
else if(numbers[l]+numbers[r]>target)
r--;
}
}
};