problem

​219. Contains Duplicate II​

solution1

219. Contains Duplicate II_i++

219. Contains Duplicate II_i++_02

class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
for(int i=0; i<nums.size(); i++)//err
{
for(int j=i+1; j<nums.size(); j++)
{
if(nums[i]==nums[j] && j-i<=k) return true;
}
}
return false;

}
};

View Code

​Time Limit Exceeded​

solution2:MAP

Hashmap

219. Contains Duplicate II_i++

219. Contains Duplicate II_i++_02

class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
map<int, int> hashmap;
for(int i=0; i<nums.size(); i++)
{
if(hashmap.find(nums[i])!=hashmap.end() && i-hashmap[nums[i]]<=k)
{
return true;
}
hashmap[nums[i]] = i;
}
return false;
}
};

View Code

solution3:SET

 

class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
set<int> myset;
for(int i=0; i<nums.size(); i++)
{
if(i>k) myset.erase(nums[i-k-1]);
if(myset.find(nums[i])!=myset.end()) return true;
myset.insert(nums[i]);//
}
return false;
}
};

 

 

参考

1. ​​Leetcode_Contains Duplicate II​​;