2020-8-15 Daily reading notes-the sum of two numbers

2020-8-15 Daily reading notes-the sum of two numbers

Insert picture description here
Use unordered_map to construct a mapping, and directly store target-nums[i] (that is, the complement corresponding to the current element). When traversing nums[i], see if nums[i] exists in the hash table.

class Solution {
    
    
public:
    vector<int> twoSum(vector<int>& nums, int target) 
    {
    
         
        unordered_map<int, int> hm;
        for(int i = nums.size() - 1; i >= 0; --i)
        {
    
    
            auto iter = hm.find(nums[i]);
            if(iter != hm.end())
                return {
    
    i, iter->second};
            int diff = target - nums[i];
            hm[diff] = i;
        }
        return {
    
    };
    }
};

Guess you like

Origin blog.csdn.net/weixin_45336082/article/details/108029974