[leetcode] Two Sum

Two Sum

使用hash

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        unordered_map<int,int> mapIndex;
        vector<int> res;
        for(int i=0;i<numbers.size();i++){
            mapIndex[numbers[i]]=i;//key:值;value:索引
        }
        
        for(int i=0;i<numbers.size();i++){
            int gap=target-numbers[i];
            if(mapIndex.find(gap)!=mapIndex.end()&&mapIndex[gap]>i){
                res.push_back(i+1);//序号从1开始
                res.push_back(mapIndex[gap]+1);
                break;//找到后退出
            }
        }
        return res;
    }
};



你可能感兴趣的:([leetcode] Two Sum)