很简单的双指针,两边夹准则就行,而且是递增序列,必须双指针了。
class Solution {
public:
vector<int> FindNumbersWithSum(vector<int> array,int sum) {
//找两个数的啥啥,就考虑双指针
vector<int> res;
if(array.size() < 2) return res;
int low = 0, high = array.size()-1;
int product = INT_MAX;
while(low<high){
//不能等于,因为low=high就是同一个数字了
if(array[low] + array[high] == sum){
if(array[low]*array[high] < product){
res.clear();
res.push_back(array[low]);
res.push_back(array[high]);
product = array[low] * array[high];
}
low++;
}
else if(array[low] + array[high] < sum){
low++;
}
else{
high--;
}
}
return res;
}
};