和为S的两个数字

题目:输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。

这道题我们用unordered_set来做,读入一个数x,我们就把它插入到unordered_set中,并在哈希表中看一下sum-x 是不是已经在unordered_set中存在了,如果已经存在,并且题目已知数组是递增排序的,所以sum-x一定是小于x的。那么这两个数就找到了,输出(sum-x , x)。但题目还要求如果有多对,输出乘积最小的,因此另开一个二维数组res记录答案对,每次找到符合条件的答案对,就比较这个答案对和之前答案对的乘积的大小,如果新的答案对的乘积更小,就把原来的答案对pop_back出去,让新的进来。最后输出res[0]就好了。

c++代码如下:

 1 class Solution {
 2 public:
 3     vector<int> FindNumbersWithSum(vector<int> array,int sum) {
 4         vector<vector<int>> res;
 5         unordered_set<int> hash;
 6         int mul = INT_MAX;
 7         for(auto x : array){
 8             hash.insert(x);
 9             if(hash.count(sum - x)){
10                 if(x * (sum - x) < mul){
11                     mul = x * (sum - x);
12                     if(res.size()) res.pop_back();
13                     res.push_back(vector<int>{sum - x, x});
14                 }
15             }
16         }
17         if(res.empty()) return vector<int>({});
18         return res[0];
19     }
20 };
原文地址:https://www.cnblogs.com/hellosnow/p/12094450.html