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 j is at most k.
Subscribe to see which companies asked this question
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
map<int, int> auxMap; //value, index map
for (int i=0; i<nums.size(); i++)
{
if (auxMap.find(nums[i]) == auxMap.end())
{
auxMap[nums[i]] = i;
}
else
{
if (i - auxMap[nums[i]] <=k)
return true;
auxMap[nums[i]] = i;// 和之前的nums[i] 相距的距离>k,所以不需要之前的nums[i], 重新把现在的作为key value
}
}
return false;
}
};