c++
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
if (nums.empty() || nums.size()<=1)
return false;
unordered_set<int> dict;//faster than set<int>
for (size_t i = 0; i < nums.size(); ++i) {
if (dict.find(nums[i]) != dict.end())
return true;
dict.insert(nums[i]);
if (dict.size() > k)
dict.erase(dict.find(nums[i - k]));
}
return false;
}
};
python
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
dict = {}
for i in xrange(len(nums)):
if dict.get(nums[i], 'N/A')!='N/A':
return True
dict[nums[i]] = 1;
if len(dict)>k:
dict.pop(nums[i-k])
return False
reference:
https://leetcode.com/discuss/100633/7-lines-cpp-solution-32ms-easy-to-understand