167. 两数之和 II - 输入有序数组 - 力扣(LeetCode)
这儿的重点是升序排列。
利用升序特点的二分查找,因为升序,查找范围会缩小的很快。
public:
//在low~high中查找第一个值大于等于给定值的元素下标
int bsearch(vector<int> &vec, int low, int high, int value){
while(low <= high){
int mid = low + ((high-low)>>1);
if(vec[mid] >= value){
// mid == low代表为最左边的哪个
if(mid == low || vec[mid-1] < value) return mid;
else high = mid - 1;
}else
low = mid + 1;
}
return -1;
}
vector<int> twoSum(vector<int>& numbers, int target) {
int n = numbers.size(), index = n;
//最后一个元素不用考虑
for(int i = 0; i < n-1; ++i){
int tmp = bsearch(numbers, i+1, index-1, target-numbers[i]);
if(tmp == -1) continue;
index = tmp;
if(numbers[index] == target - numbers[i]) return {i+1, index+1};
}
return {};
}
};
二分法还可以这样:
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
for (int i = 0; i < numbers.size(); ++i) {
int low = i + 1, high = numbers.size() - 1;
while (low <= high) {
int mid = (high - low) / 2 + low;
if (numbers[mid] == target - numbers[i]) {
return {i + 1, mid + 1};
} else if (numbers[mid] > target - numbers[i]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
}
return {};
}
};
再优化,还是利用升序的特点,双指针:
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int l = 0, r = numbers.size()-1;
while(l < r){
if(numbers[l]+numbers[r] == target) return {l+1, r+1};
else if(numbers[l]+numbers[r] > target) --r;
else ++l;
}
return {};
}
};