#Leetcode每日不知道多少题之基础知识要运用!

A. 存在重复元素 II(219)

给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k

示例 1:

输入:[1,2,3,1], k = 3

输出:true

示例 2:

输入:[1,0,1,1], k = 1

输出:true

示例 3:

输入:[1,2,1], k = 0

输出:false

 

分析:

    这道题其实不难,最基础的想法就是直接暴力......Too naive!骚年!这么一打眼就能看出来会TLE的做法肯定不对啊......(我是菜鸡TAT)

这道题提醒我们使用一种STL结构,哈希表。嘿嘿嘿不容易想到吧,就是这么坑。(也可能是我太菜了)


代码:

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        if(k <= 0 || nums.size() < 1)
            return false;
        unordered_map<int, int> m;
        for(int i = 0; i < nums.size(); i++)
        {
            if(m.find(nums[i]) == m.end())
            {
                m.insert({nums[i], i});
            }
            else if(i - m[nums[i]] <= k)
                return true;
            else 
                m[nums[i]] = i;
        }
        return false;
    }
};

关于哈希表的其他 unordered_map——摘自C++ Reference

Unordered maps are associative containers that store elements formed by the combination of a key value and a mapped value, and which allows for fast retrieval of individual elements based on their keys.

In an unordered_map, the key value is generally used to uniquely identify the element, while the mapped value is an object with the content associated to this key. Types of key and mapped value may differ.

unordered_map containers are faster than map containers to access individual elements by their key, although they are generally less efficient for range iteration through a subset of their elements.

......算了我找到一个写的比较详细的CSDN博客......点击打开链接,还有这个......点击打开链接......

我简单概括一下:unordered_map实际上相当于一个无序映射,可以快速地根据键值找到元素。unordered_map容器比map容器能够更快地通过它们的键来访问各个元素,但是它们通过其元素的子集进行范围迭代通常效率较低。


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值