题意: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 jis at most k.
窗口思想
定义一个长度最大为k的滑动窗口,用一个set维护窗口内的数字判断是否出现重复,使用两个指针start和end标记滑动窗口的两端,
初始都是0,,然后end不断进行扩展,扫描元素判断是否出现重复元素,直到发现end-start>k, 就开始移动start,并且在set中移除对应的元素。
如果以为扫描到数组末尾还没有发现重复元素,那就可以返回false。
这样不会超时
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
set<int> hash;
int start=0;
for(int i=0;i<nums.size();++i)
{
if(i<=k)
{
if(hash.find(nums[i]) != hash.end())
return true;
else
hash.insert(nums[i]);
}
else
{
hash.erase(nums[start]);
start++;
if(hash.find(nums[i]) != hash.end())
return true;
else
hash.insert(nums[i]);
}
}
return false;
}
};
更精简的代码
set<int> cand;
for (int i = 0; i < nums.size(); i++) {
if (i > k) cand.erase(nums[i-k-1]);
if (!cand.insert(nums[i]).second) return true;//有重复值,seconde为false
}
return false;
浙公网安备 33010602011771号