219. Contains Duplicate II
2026/1/12小于 1 分钟约 252 字
219. Contains Duplicate II
难度: Easy
题目描述
Given an integer array nums and an integer k, return true if there are two distinct indicesi and j in the array such that nums[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 <= 105-109 <= nums[i] <= 1090 <= k <= 105
解题思路
代码实现
解决方案
java
func containsNearbyDuplicate(nums []int, k int) bool {
m := make(map[int]int)
for i := 0; i < len(nums); i++ {
if pre, ok := m[nums[i]]; ok {
if i-pre <= k {
return true
}
}
m[nums[i]] = i
}
return false
}