167.两数之和2-输入有序数组
我的解法:
双指针法:
- low、high两个指针分别从数组左右两端向中间遍历;
- 若low、high所指元素之和大于target,则将high指针左移;
- 若low、high所指元素之和小于target,则将low指针右移;
- 若low、high所指元素之和等于target,则已找出结果
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> res;
int n = numbers.size();
int low = 0, high = n - 1;
while(low < high){
if(numbers[low] + numbers[high] == target){
res.push_back(low + 1);
res.push_back(high + 1);
break;
}
else if(numbers[low] + numbers[high] > target){
high--;
}
else{
low++;
}
}
return res;
}
};