[LeetCode] Contains Duplicate II
2015-06-02 23:18
507 查看
Well, the basic idea is fairly straightforward. We maintain a mapping
mpfrom a value in
numsto 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
iis larger than the old index
mp[nums[i]]), we return
trueor update the index (
mp[nums[i]] = i). If all the elements have been visited and we have not returned
true, we will return
false.
bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_map<int, int> mp; for (int i = 0; i < nums.size(); i++) { if (mp.find(nums[i]) != mp.end() && i - mp[nums[i]] <= k) return true; mp[nums[i]] = i; } return false; }
相关文章推荐
- hdu1848 Fibonacci again and again(SG函数博弈)
- Mac系统安装Rails
- #219 Contains Duplicate II
- [leetcode] Contains Duplicate III
- 大数据引发的联想--人工智能
- 暴力/DP Codeforces Beta Round #22 (Div. 2 Only) B. Bargaining Table
- opencv源码研究: icvGetHaarTrainingDataFromBG和icvGetHaarTrainingDataFromVec的区别
- LightOJ-1138 Trailing Zeroes (III) (二分搜索)
- UVa 514 - Rails
- Solr使用SolrJ出现Lock obtain timed out: NativeFSLock
- http://blog.csdn.net/wzzvictory/article/details/16994913
- manage_data_in_containers
- 使用Rails 4.2+ 测试异步邮件系统
- 经常发Email,你知道“抄送(Cc)”、“密送(Bcc)”的意思吗?
- rails测试错误 false to respond to ‘false?'
- LeetCode219:Contains Duplicate II
- LeetCode_11---Container With Most Water
- setContentView(R.layout.activity_main) Error解决方法
- [ERROR] Failed to execute goal org.apache.maven.plugins:maven-install-plugin:2.3.1:
- email验证