Given an array of integers andaninteger k, find out whether there are two distinct indices i and j inthe array such that nums[i] = nums[j] andthe absolute difference between i and j is at most k.
Subscribe to see which companies asked this question.
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> m;
for(int i = 0; i < nums.size(); ++i){
if(m.find(nums[i]) != m.end() && i - m[nums[i]] <= k)
returntrue;
else m[nums[i]] = i;
}
returnfalse;
}
};