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

【LeetCode】219. Contains Duplicate II

2015-07-07 20:08 411 查看
Contains Duplicate II

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.

使用unordered_map记录每个值与对应index位置,当出现重复值时,比较index距离是否在k之内,

注意index的更新

class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> m;  // value --> index
for(int i = 0; i < nums.size(); i ++)
{
if(m.find(nums[i]) == m.end())
m[nums[i]] = i;
else
{
if(i - m[nums[i]] <= k)
return true;
else
m[nums[i]] = i; // update the index
}
}
return false;
}
};


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