#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> FindNumbersWithSum(vector<int> array, int sum) {
//1 2 3 4 5 6 7
int i = 0;
int j = array.size() - 1;
int max = 0x7fffffff;
vector<int> v;
while (i<j)
{
if (array[j] + array[i]>sum)j--;
else if (array[j] + array[i]<sum)i++;
else
{
if (array[i] * array[j] < max)
{
v.clear();
max = array[i] * array[j];
v.push_back(array[i]);
v.push_back(array[j]);
}
i++;
j--;
}
}
return v;
}
};
int main()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
v.push_back(6);
v.push_back(7);
Solution sl;
vector<int> result = sl.FindNumbersWithSum(v,10);
for (int i = 0; i < result.size(); i++)
{
cout << result[i] << " ";
}
cout << endl;
return 0;
}
笔试题:求数组中和为sum的乘积最小的一对组合
最新推荐文章于 2021-08-11 22:51:07 发布