LeetCode 1. Two Sum

给定数组和一个值,求数组中两个数和为该值时,两个数的标号。结果单一,不能选取同一个数两次。

Keywords: O(n); unordered_map; hash

#include <unordered_map>
#include <cstdio>
using namespace std;

class Solution {
public:

vector<int> twoSum(vector<int> &nums, int target) {
    vector<int> ans;
    int n=nums.size();
    unordered_map <int,int>m;
    for (int i=0;i<n;i++){
        if (m.find(target-nums[i])!=m.end()) {
            ans.push_back(m.find(target-nums[i])->second);
            ans.push_back(i);
            return ans;
        }
        m.insert(pair<int,int>(nums[i],i));
    }
}
    
};

 

思路:

  因为没给数据范围,一开始想到的是类似桶排那样,开数组flag[],将给定的数组中出线的值在flag中标记。然后循环判断target-x是否存在。

  实际上桶排也是一种hash,只不过hash函数简单,即hash=x。因为不考虑元素重复的问题,加快检索速度,采用 unordered_map 存储(类似hash)。另外solution中也提到,可以one-pass loop完成,即在将值添加到map的时候就判断target-x是否存在即可。

 

问题:

  1. map<int,int>::iterator iter; 可以写成 auto iter;

  2. 可以直接 return{m.find(target-nums[i])->second , i};

  3. STL中,vector 不能用 [] 赋值,只能 push_back(); map.find() 是对第一个关键字进行检索,不是第二个。

posted @ 2018-05-31 17:30  Travelller  阅读(92)  评论(0编辑  收藏  举报