标签:二分查找 二分 while public == 一个 pair 个数 和为s的两个数字
在一个有序数组里找两个和为s的数字
sum
sum > target
,说明太大,则右边的指针应该往左走sum < targe
t,说明太小,则左边的指针应该往右走class Solution {
public:
int find_pair(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while(left <= right) {
int mid = left + (right - left) / 2;
if(nums[mid] == target) {
return mid;
}else if(nums[mid] > target) {
right = mid - 1;
}else {
left = mid + 1;
}
}
return -1;
}
vector<int> twoSum(vector<int>& nums, int target) {
for(auto n: nums) {
int p = find_pair(nums, target - n);
if(p != -1) {
return {n, nums[p]};
}
}
return {};
}
};
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int cur1 = 0, cur2 = nums.size() - 1;
while(cur1 != cur2) {
int sum = nums[cur1] + nums[cur2];
if(sum == target) {
return {nums[cur1], nums[cur2]};
}else if(sum > target) {
cur2--;
}else {
cur1++;
}
}
return {};
}
};
标签:二分查找 二分 while public == 一个 pair 个数 和为s的两个数字
原文地址:https://www.cnblogs.com/MartinLwx/p/14398053.html