//解法一:超时
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
int len=nums.size();
if(len<=1)
return false;
for(int i=0;i<len-1;i++)
{
for(int j=i+1;j<len;j++)
{
if ((nums[j]==nums[i])&&(j-i<=k))
return true;
}
}
return false;
}
};
//解法2
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
map<int,int> m;
map<int,int>::iterator iter;
if(nums.size()>1)
{
for(int i=0;i<nums.size();i++)
{
iter=m.find(nums[i]);
if(iter!=m.end())
{
if(i - iter->second<=k)
return true;
else
m.erase(iter);
}
m.insert(pair<int,int>(nums[i],i));
}
}
return false;
}
};