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() 是对第一个关键字进行检索,不是第二个。

转载于:https://www.cnblogs.com/travelller/p/9117904.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值