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容器能够更快地通过它们的键来访问各个元素,但是它们通过其元素的子集进行范围迭代通常效率较低。