Timeline
Timeline
2025-11-13
init
Hash table
Problem:
123456789101112131415161718192021222324252627282930313233 | using std::unordered_map;using std::vector;class Solution { public: bool containsNearbyDuplicate(vector<int> &nums, int k) { int i, j, n = nums.size(); unordered_map<int, vector<int> > num2index; for (i = 0; i < n; i++) num2index[nums[i]].push_back(i); for (auto &[_, index_vec] : num2index) { if (index_vec.size() > 1) { n = index_vec.size(); for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if (std::abs(index_vec[i] - index_vec[j]) <= k) { return true; } } } } } return false; }}; |
A single pass is enough. During the traversal, save the last occurrence of the same value, because the index of the last same value is closest to the current index, so it is most likely to satisfy .
1234567891011121314151617181920 | using std::vector;using std::unordered_map;class Solution {public: bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_map<int,int> lastIndex; for (int i = 0; i < nums.size(); ++i) { if (lastIndex.count(nums[i]) && i - lastIndex[nums[i]] <= k) return true; lastIndex[nums[i]] = i; } return false; }}; |
