题目描述
输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
输出描述:
对应每个测试案例,输出两个数,小的先输出。
tips: 使用两个index,只需o(n)的复杂度
class Solution {
public:
vector<int> FindNumbersWithSum(vector<int> array,int sum) {
int index1=0;
int index2=array.size()-1;
vector<int> res;
if(array.size()<2) {
return res;
} else if(array.size()==2) {
if(array[0]+array[1]==sum) {
return array;
} else {
return res;
}
}
int add=0;
while(index1<index2) {
add=array[index1]+array[index2];
if(add>sum) {
index2--;
} else if(add<sum) {
index1++;
} else {
if(res.size()!=0) {
if(array[index1]*array[index2]<res[0]+res[1]) {
res.clear();
res.push_back(array[index1]);
res.push_back(array[index2]);
}
} else {
res.push_back(array[index1]);
res.push_back(array[index2]);
}
index2--;
}
}
return res;
}
};