从排序数据中找和为定值的方法,一般是左右逼近,时间复杂度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
本文介绍了一种在已排序数组中寻找两个数使它们的和等于特定目标值的高效算法。采用左右指针逼近的方法,时间复杂度为O(N)。通过不断调整指针位置来实现快速匹配。
366

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



