从排序数据中找和为定值的方法,一般是左右逼近,时间复杂度O(N)
/*
* @lc app=leetcode id=167 lang=cpp
*
* [167] Two Sum II - Input array is sorted
*/
// @lc code=start
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> ans(2,0);
int N = numbers.size();
if(N <= 1) return ans;
int L = 0;
int R = N-1;
while(L<R){
if(numbers[L] + numbers[R] == target){
ans[0] = L+1;
ans[1] = R+1;
return ans;
}
if(numbers[L] + numbers[R] < target){
L++;
}
if(numbers[L] + numbers[R] > target){
R--;
}
}
return ans;
}
};
// @lc code=end