Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between iand j is at most k.
解决思路:将数组的值和下标分别作为键值对存储到Map中,遍历nums时使用Map的find查找是否有相同的元素,如果没有则添加该键值对,如果有相同的元素则将他们的下标差与K对比,大于k,修改map中该元素对应的value,即下标,小于K,返回true。(Time: 72ms)
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
map<int, int> mapset;
if(nums.size()<=1) return false;
for(int i=0; i<nums.size(); ++i)
{
if(mapset.find(nums[i])==mapset.end())
{
mapset[nums[i]]=i;
}
else if(abs(mapset[nums[i]]-i) <=k)
{
return true;
}
else
{
mapset[nums[i]]=i;
}
}
return false;
}
};