Sword Finger Offer Question 42
The topic is as follows
The idea and code are as follows
Each value is searched for if sum-array[I] exists. If it exists, it means it is found. Then, let’s see if the product should be updated
and then store it in the map.
Since the title says that the product of two numbers is the smallest, it can’t be found. Break immediately; finish running!
unordered_map is much faster than map! ! !
#include<unordered_map>
class Solution {
public:
vector<int> FindNumbersWithSum(vector<int> array,int sum) {
unordered_map<int,int> m;
vector<int> res;
int max=0xFFFFFFF;
for(int i=0;i<array.size();i++){
if(m.find(sum-array[i])!=m.end()){
if((sum-array[i])*array[i]<max){
res.clear();
res.push_back(sum-array[i]);
res.push_back(array[i]);
max=(sum-array[i])*array[i];
}
}else{
m[array[i]]=1;
}
}
return res;
}
};