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.
【思路】用map实现,寻找具有相同关键值的下标差值是否小于等于k.
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
map<int, int>int_map;
for(int i=0; i < nums.size(); i++)
{
if(int_map.find(nums[i])==int_map.end())
int_map[nums[i]] = i;
else
{
if((i - int_map[nums[i]])<=k)
return true;
else
int_map[nums[i]] = i;
}
}
return false;
}
};