[剑指 offer] JT42---Sum two numbers (two times the hash table, the order of appearance is very important)

The topic is as follows

Insert picture description here

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;
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_42136832/article/details/115027307