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].

 题意:给定的数组,找到其中两个数,满足和为给定的值,返回这两个数的下标

思路:利用哈希映射,遍历数组,一边向哈希表中插入数值,下标的键值对,一遍在哈希表里面查找有没有(target-这个数),如果有的话,把两个数的下标添加到数组,返回。

class Solution {
public:
    //数组的数值,下标作为键值对保存到map
    //遍历数组的时候,在map 中找target-num,如果能找到就把坐标push进ans,两个下标的顺序无所谓
    //如果没有找到,就插入新的键值对
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int,int> m;
        vector<int> ans;
        for(int i=0;i<nums.size();i++){
            if(m.count(target-nums[i]) && m[target-nums[i]]!=i){  //这里没有判断和i相等也可以
                ans.push_back(i);
                ans.push_back(m[target-nums[i]]); 
            }
            else m[nums[i]]=i;
        }
        return ans;
        
        
    }
};