记录Leetcode第一天(Two Sum和unordered_map)

记录LeetCode第一天(Two Sum)

1.题目

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.

2.例子

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

3.代码

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) 
    {
        std::vector<int> values;//定义一个空的int类型vector
        int n=nums.size();//取到导入nums的长度
        unordered_map<int,int> m;//int类型的key和int类型的T,图命名为m
        for(int i=0;i<n;++i)//遍历第一个数
        {
            if(m.find(target - nums[i])!=m.end())//在图里面找target-当前第一个数,找不到返回end
            {
                values.push_back(m[target - nums[i]]);//在vector里面加一个数
                values.push_back(i);//再往后加一个
                break;
            }   
            m[nums[i]] = i;//如果没找到,就把数加到表里面
        }                            
    return values;
    }
};
            

4. unordered_map

我理解的是,排列方式正好和数组相反。比如在一个数组a中,找第i项,值为n。也就是a[i]=n。而在这里面就是一个unordered_map 名字为a中,找n(key),里面的值为i(T). 就像上面代码里面的 m[nums[i]] = i;
这样说的话,就像在数组里面不能有相同的项数i一样,在unordered_map里面不能有相同的key
http://www.cplusplus.com 里可以找到

member typedefinition
key_typethe first template parameter (Key)
mapped_typethe second template parameter (T)

参考

https://www.cnblogs.com/tp-16b/p/9156810.html 超级详细讲解
代码用到的是里面的 (2)operator[]接口 部分

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值