LeetCode 1. Two Sum -- HashTable

LeetCode 1. Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解法:

  

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int,int> m;
        vector<int> res;
        
        for(int i = 0; i< nums.size(); i++)
            m[nums[i]] = i;//实现数字到索引的映射
        
        for(int i = 0; i < nums.size(); ++i){
            int t = target - nums[i];
            
            if(m.count(t) && m[t] != i){   //  可以看c++ primer 第389页 //并且防止出现 [3 2 4] target = 6 返回0,0
                res.push_back(i);
                res.push_back(m[t]);
                break;
            }
        }
        return res;
        
    }
};

 

posted @ 2019-09-23 10:53  3/8  阅读(86)  评论(0编辑  收藏  举报