219. Contains Duplicate II
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.
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_set<int> res;
for(int l=0;l<nums.size();l++)
{
if(res.find(nums[l])!=res.end()){
return true;
}
res.insert(nums[l]);
if(res.size()==k+1){
res.erase(nums[l-k]);
}
}
return false;
}
};
26ms