标签:
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 isatisfy 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 }
[LeetCode] Contains Duplicate II
标签:
原文地址:http://www.cnblogs.com/jcliBlogger/p/4548006.html