219. Contains Duplicate II
Difficulty: Easy
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.
思路
217题Contains Duplicate中,使用了unordered_set容器。
在本题中,不仅要记录元素的值,还要记录元素在nums中的下标。因此,使用unordered_map容器。
同样,顺序遍历nums中元素,调用find判断map容器中是否存在该元素;
不存在则给map添加键-值元素对,键为该元素值,值为该元素的下标值;
存在,则还需判断目前的下标值与容器中存储的下标值是否差值不大于k;
不大于k,就直接返回true;大于就继续遍历nums。
代码
[C++]
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> mymap;
int i = 0;
for (vector<int>::iterator it = nums.begin(); it != nums.end(); ++it, ++i) {
if (mymap.find(*it) != mymap.end()) {
if (i - mymap[*it] <= k)
return true;
}
mymap[*it] = i;
}
return false;
}
};