码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Contains Duplicate II

时间:2015-06-03 00:43:26      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!