0219.cpp (476B)
1 class Solution { 2 public: 3 bool containsNearbyDuplicate(vector<int> &nums, int k) { 4 unordered_set<int> us; 5 int n = nums.size(), i; 6 for (i = 0; i <= k && i < n; i++) { 7 if (us.count(nums[i])) return true; 8 us.insert(nums[i]); 9 } 10 11 for (; i < n; i++) { 12 us.erase(nums[i - k - 1]); 13 if (us.count(nums[i])) return true; 14 us.insert(nums[i]); 15 } 16 17 return false; 18 } 19 };