leetcode Contains Duplicate II
2015-12-14 20:45
441 查看
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.
这道题自己最后没有做出来,看的是【陆草纯】的解法。
如果是JAVA的hashmap的话很简单,但是C++没有,之前我也想过用map按值排序,半天实现不了。
先讲一下陆草纯的解法:
构建一个map,如果nums里的元素在map里没有出现过的话,就先保存下标。
如果出现过的话,就比较一下下标差值是否小于k。然后更新下标(每次都储存每个元素的最新下标)
这道题自己最后没有做出来,看的是【陆草纯】的解法。
如果是JAVA的hashmap的话很简单,但是C++没有,之前我也想过用map按值排序,半天实现不了。
先讲一下陆草纯的解法:
构建一个map,如果nums里的元素在map里没有出现过的话,就先保存下标。
如果出现过的话,就比较一下下标差值是否小于k。然后更新下标(每次都储存每个元素的最新下标)
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_map<int,int> vec; int s=nums.size(); if(s==0||k==0) return false; for(int i=0;i<s;i++){ if(vec.find(nums[i])==vec.end()){ vec[nums[i]]=i; } else { if(i-vec[nums[i]]<=k) return true; vec[nums[i]]=i; } } return false; } };
相关文章推荐
- 【Beta】Daily Scrum Meeting第七次
- 【Beta】Daily Scrum Meeting第七次
- 网页访问报错503,Service Temporarily Unavailable
- 出现conversion failed: could not save output document; OOo errorCode:错误
- 2015 ACM/ICPC Asia Regional Shanghai Online --HDU 5478
- itext添加标题(heading)--http://www.cnblogs.com/anrainie/archive/2012/03/21/2410013.html
- tools:context=".MainActivity的作用
- composer update Deprecation Notice: The Composer\Package\LinkConstraint\MultiConstraint class is dep
- Gradle sync failed: Gradle DSL method not found: 'compile()'
- 修复 Visual Studio Error “No exports were found that match the constraint”
- FAILED BINDER TRANSACTION
- main函数的简介
- Bonfire: DNA Pairing
- tools:context=".MainActivity的作用
- Spark 连接 hdfs时:Call From to master:8020 failed on connection exception:
- VVDI Benz VVDI MB TOOL key programmer Latest Technical details
- Scala:trait
- Dell idrac8 设置Email 邮件报警
- 使用Genymotion调试时报错Installation error: INSTALL_FAILED_CPU_ABI_INCOMPATIBLE
- svn cleanup failed问题解决