跳至主要內容

219. Contains Duplicate II


219. Contains Duplicate IIopen in new window

🟢   🔖  数组 哈希表 滑动窗口  🔗 LeetCodeopen in new window

题目

Given an integer array nums and an integer k, return true _if there are two distinct indices _i andj in the array such thatnums[i] == nums[j] and abs(i - j) <= k.

Example 1:

Input: nums = [1,2,3,1], k = 3

Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1

Output: true

Example 3:

Input: nums = [1,2,3,1,2,3], k = 2

Output: false

Constraints:

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • 0 <= k <= 10^5

题目大意

如果数组里面有重复数字,并且重复数字的下标差值小于等于 K 就输出 true,如果没有重复数字或者下标差值超过了 K ,则输出 flase

解题思路

这道题可以维护一个只有 K 个元素的 map,每次只需要判断这个 map 里面是否存在这个元素即可。如果存在就代表重复数字的下标差值在 K 以内。map 的长度如果超过了 K 以后就删除掉 i-k 的那个元素,这样一直维护 map 里面只有 K 个元素。

代码

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {boolean}
 */
var containsNearbyDuplicate = function (nums, k) {
	const map = new Map();
	for (let i = 0; i < nums.length; i++) {
		if (map.has(nums[i])) return true;
		map.set(nums[i], 1);
		if (map.size > k) map.delete(nums[i - k]);
	}
	return false;
};

相关题目

相关题目
- [217. 存在重复元素](./0217.md)
- [220. 存在重复元素 III](https://leetcode.com/problems/contains-duplicate-iii)