219. Contains Duplicate II
2016-04-11 15:40
549 查看
题目
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 jis
at most k
分析
.记录每个元素的第一次出现位置,当它第二次出现时判断与第一次出现位置距离是否小于等于k,若不符合,则用第二次出现位置替换第一次出现位置继续进行比较。
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int,int> map;
for(int i = 0; i < nums.size(); i++)
{
if(map.count(nums[i]) && (i - map[nums[i]] <= k))
return true;
map[nums[i]] = i;
}
return false;
}
};
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 jis
at most k
分析
.记录每个元素的第一次出现位置,当它第二次出现时判断与第一次出现位置距离是否小于等于k,若不符合,则用第二次出现位置替换第一次出现位置继续进行比较。
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int,int> map;
for(int i = 0; i < nums.size(); i++)
{
if(map.count(nums[i]) && (i - map[nums[i]] <= k))
return true;
map[nums[i]] = i;
}
return false;
}
};
相关文章推荐
- 【poj 1691】Painting A Board
- 开发错误记录5:Failed to resolve: com
- 调用 webservice 出现:WSDLReader:Loading of the WSDL file failed HRESULT=0×80040154: 没有注册类别 解决方案
- open(\"/dev/graphics/fb0\") failed!
- 自定义View时,用到Paint Canvas的一些温故,讲讲用路径绘画实现动画效果(基础篇 三)
- 自定义View时,用到Paint Canvas的一些温故,讲讲用路径绘画实现动画效果(基础篇 三)
- 配置Mailgraph_ext,使用Extman的图形日志
- LeetCode OJ 219.Contains Duplicate 2
- https请求 CFNetwork SSLHandshake failed (-9807) A connection failure occurred: SSL problem
- LeetCode OJ 217.Contains Duplicate
- Failed reading log event, reconnecting to retry
- Markov Chain(bate)
- 关于 Gradle failed: already disposed module 的问题
- maertSataDmorfnaideMdniF.295
- ZOJ 3780 Paint the Grid Again-贪心模拟/拓扑排序
- AIDL
- 下一代机器学习-在浏览器中训练深度学习模型Next Generation Machine Learning - Training Deep Learning Models in a Browser
- trail particle制作血管
- leetcode 11 Container With Most Water
- Argument list too long: recursive header expansion failed at