算法之x数之和

一 两数之和

cpp 复制代码
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
       unordered_map<int,int> hashMap;
       int len = size(nums);
       for(int i =0; i < len; i++){
        auto it = hashMap.find(target-nums[i]);
        if(it != hashMap.end()){
            return {it->second,i};
        }
        hashMap[nums[i]] = i;
       } 
       return {};
    }
};

【1】unordered_map

【2】数组的值是key,数组的下标是value,存到hashmap中

【3】找到key则return结果,否则存储当前遍历的节点{key,value}

【4】find -> auto it && hashmap.end

二 三数之和