题解 | #和为S的两个数字#
和为S的两个数字
https://www.nowcoder.com/practice/390da4f7a00f44bea7c2f3d19491311b
class Solution {
public:
int binarySearch(vector<int> array, int target, int l, int r) {
while (l <= r) {
int mid = l + (r - l) / 2;
if(array[mid] < target)
{
l = mid + 1;
}
else if(array[mid] > target){
r = mid - 1;
}
else{
return target;
}
}
return -1;
}
vector<int> FindNumbersWithSum(vector<int> array, int sum) {
vector<int> res;
for(int i = 0;i<array.size();i++)
{
int leaveValue = binarySearch(array, sum-array[i], i+1, array.size()-1);
if(leaveValue == -1){
continue;
}
else{
res.push_back(array[i]);
res.push_back(leaveValue);
return res;
}
}
return {};
}
};
先确定第一个数,然后在剩余的数组中进行二分查找。

腾讯成长空间 5193人发布