[LeetCode] Contains Duplicate II
Well, the basic idea is fairly straightforward. We maintain a mapping mp
from a value in nums
to its position (index) i
. Each time we meet an unseen value, we add it to the map (mp[nums[i]] = i
). Otherwise, depending on whether the recorded index mp[nums[i]]
and the current index i
satisfy i - mp[nums[i]] <= k
(node that the new index i
is larger than the old indexmp[nums[i]]
), we return true
or update the index (mp[nums[i]] = i
). If all the elements have been visited and we have not returned true
, we will return false
.
1 bool containsNearbyDuplicate(vector<int>& nums, int k) { 2 unordered_map<int, int> mp; 3 for (int i = 0; i < nums.size(); i++) { 4 if (mp.find(nums[i]) != mp.end() && i - mp[nums[i]] <= k) 5 return true; 6 mp[nums[i]] = i; 7 } 8 return false; 9 }