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.
思路:
哈希表查找就好,将数组数值和下标挂钩,如果发现表中存在该数值,比较下标距离即可。注意,这题是证明是否存在这种组合,而不是所有重复数字都得满足,存在即可。
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; }
相关文章推荐
- NSSearchPathForDirectoriesInDomains用法--转自平静大海
- 217. Contains Duplicate
- HDOJ 1789 Doing Homework again
- HDOJ 2124 Repair the Wall(修城墙,贪心)
- POJ 1995 Raising Modulo Numbers
- HDU Problem - 1789 Doing Homework again【贪心】
- poj 1995 Raising Modulo Numbers
- Doing Homework again(贪心)
- IDR_MAINFRAME中各个字段的含义
- HDU1789 Doing Homework again(贪心+sort)
- Trailing Zeroes (III)<二分>
- HDU 2124Repair the Wall(贪心)
- POJ1995Raising Modulo Numbers
- windows 画图工具 —— mspaint 的使用
- poj1995Raising Modulo Numbers(快速幂+同余定理)
- Raising Modulo Numbers
- POJ-1995 Raising Modulo Numbers
- HDU 5319 Painter
- hdu 5732 subway(2016 Multi-University Training Contest 1 1010)
- 【杭电1789】Doing Homework again贪心(还不太懂)