您的位置:首页 > 大数据 > 人工智能

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: