当前位置:网站首页>Niuke.com: sum of two numbers

Niuke.com: sum of two numbers

2022-06-10 22:45:00 lsgoose

When I saw this question, my first reaction was to do pair, Number and index . Then sort the numbers , Then double pointer .

It turns out that there is something as magical as a hash table . So we can use a hash table to store values and indexes .

Ideas as follows :

Traverse the entire array :

1. Complement the current number to get temp

2.temp Not in hash table , Then put the current number and its index into the hash table

3. otherwise , Find two numbers , Add... To the index 1 Put the label of into the answer , end

class Solution {
public:
    /**
     * 
     * @param numbers int integer vector 
     * @param target int integer  
     * @return int integer vector
     */
    vector<int> twoSum(vector<int>& numbers, int target) {
        // write code here
        vector<int> res;
        unordered_map<int, int> hash;
        for(int i=0;i<numbers.size();++i){
            int temp=target-numbers[i];
            if(hash.find(temp)==hash.end()){
                hash[numbers[i]]=i;
            }else{
                res.push_back(hash[temp]+1);
                res.push_back(i+1);
                break;
            }
        }
        return res;
    }
};

原网站

版权声明
本文为[lsgoose]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101641507082.html