题目:
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 absolute difference
between i and j is
at most k.
思路:
思想和 [Leetcode] 217 Contains Duplicate非常类型,只需要稍稍做一下改进即可:我们在哈希表中同时记录数组中每个数出现的位置。一旦发现了值相同的数,还需要判断两者的索引差距是否在k之内。如果是则直接返回true,否则我们还需要修改该数的索引(因为我们是从前往后扫描的,所以修改后的索引会有利于后续再次发现相同的数时对索引差异的判断)。算法的时间复杂度和空间复杂度都是O(n)。
代码:
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> hash;
unordered_map<int, int>::iterator it;
for (size_t i = 0; i < nums.size(); i++) {
it = hash.find(nums[i]);
if (it == hash.end()) {
hash.insert(pair<int, int>(nums[i], i));
}
else {
if (i - hash[nums[i]] <= k) {
return true;
}
it->second = i;
}
}
return false;
}
};