219. Contains Duplicate II
2015-06-03 16:58
447 查看
Given an array of integers and an integer k,
find out whether there there are two distinct indices i and j in
the array such that nums[i] = nums[j] and
the difference between iand j is
at most k.
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int,int> myMap;
for(int i = 0;i<nums.size();++i)
{
if(myMap.find(nums[i]) == myMap.end())
myMap[nums[i]] = i;
else
{
if(i-myMap[nums[i]] <=k)
return true;
else
myMap[nums[i]] = i;
}
}
return false;
}
};
find out whether there there are two distinct indices i and j in
the array such that nums[i] = nums[j] and
the difference between iand j is
at most k.
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_map<int, int> hash; for (int i= 0; i< nums.size(); ++i) { auto it = hash.find(nums[i]); if (it!= hash.end() && i-it->second <= k) return true; else hash[nums[i]]= i;//将<数值,下标>放入hash表中 } return false; } };
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int,int> myMap;
for(int i = 0;i<nums.size();++i)
{
if(myMap.find(nums[i]) == myMap.end())
myMap[nums[i]] = i;
else
{
if(i-myMap[nums[i]] <=k)
return true;
else
myMap[nums[i]] = i;
}
}
return false;
}
};
相关文章推荐
- ARC中Retain Cycle揭秘
- 217. Contains Duplicate
- AEAI DP_V3.4.0_20150601升级说明
- postfix+extmail+dovecot+ courier-authlib 实现公网邮件服务器
- 解决sublimeText3无法安装插件问题 -- There are no packages available for installation
- Leetcode Problem.217 —Contains Duplicate
- 使用NSSearchPathForDirectoriesInDomains等获取路径的方法时的注意事项
- tools:context=".MainActivity的作用
- AIX下新建账户
- 控制台应用程序的Main方法
- * failed to start daemon *
- KVM 介绍(3):I/O 全虚拟化和准虚拟化 [KVM I/O QEMU Full-Virtualizaiton Para-virtualization]
- VS2010调试 --指南 Reference from : http://blog.csdn.net/kingzone_2008/article/details/8133048
- Main函数中参数argc,argv说明
- MFC单文档工程的使用小结(CDocument, CView, CMainFrame)
- LeetCode: Contains Duplicate
- Onpaint()函数中绘图出现问题:当多次进入onpaint()发现次数达到一定程度就会出现窗口不能再重绘导致窗口内容损坏的现象
- AIDL机制实现进程间的通讯实例
- storyboard plain style unsupported in a navigation item
- document.domain 跨域问题