1.描述
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.
2.分析
用集合s存放最大距离为k之间的数组元素,依次遍历数组。
放入规则:遍历数组元素为nums[i],在集合s中查找nums[i]是否在集合中,如果在,则返回true。
取出规则:遍历数组元素为nums[i],如果i>k, 则从集合中取出nums[i-k-1]。
3.代码
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
if (k <= 0) return false;
if (k > nums.size()) k = nums.size() - 1;
unordered_set<int> s;
for (int i = 0; i < nums.size(); ++i) {
if (i > k) s.erase(nums[i-k-1]);
if (s.find(nums[i]) != s.end()) return true;
s.insert(nums[i]);
}
return false;
}
};