219. Contains Duplicate II
原创
©著作权归作者所有:来自51CTO博客作者mb62c788fd198da的原创作品,请联系作者获取转载授权,否则将追究法律责任
problem
219. Contains Duplicate II
solution1
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
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;
完