双指针
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int i=0,j=numbers.size()-1;
while(i<j){
if(numbers[i]+numbers[j]==target)return{i+1,j+1};
else if(numbers[i]+numbers[j]>target)j--;
else i++;
}
return{};
}
};
二分
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int l=0,r=numbers.size()-1;
while(l<r){
int mid=(l+r)>>1;
if(numbers[l]+numbers[mid]>target)r=mid-1;
else if(numbers[r]+numbers[mid]<target)l=mid+1;
else if(numbers[l]+numbers[r]>target)r--;
else if(numbers[l]+numbers[r]<target)l++;
else return{l+1,r+1};
}
return{};
}
};