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

219. Contains Duplicate II

2016-07-23 17:54 267 查看
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.

思路:

哈希表查找就好,将数组数值和下标挂钩,如果发现表中存在该数值,比较下标距离即可。注意,这题是证明是否存在这种组合,而不是所有重复数字都得满足,存在即可。

bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> myhash;
for (int i = 0; i < nums.size(); i++) {
if (myhash.find(nums[i]) != myhash.end()) {
int j = myhash[nums[i]];
if (i - j <= k) return true;
else myhash[nums[i]] = i;
//这里更新下标很重要,因为对于后面可能出现的重复要保证求得目前的最近的下标,看有没有可能满足要求
}
else
myhash[nums[i]] = i;
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: