05 August 2008
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 absolute difference between i and j is at most k.
Example 1:
1
2
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
1
2
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
1
2
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
第217 Contains Duplicate的延伸,加了个条件检查重复元素的索引是否超过k,没超过就返回true,同样用HashMap来存,k-v分别是元素的值和索引,检查重复的时候加一个检查条件即可。
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) {
return true;
}
map.put(nums[i], i);
}
return false;
}
}
也可以用HashSet添加值会有一个boolean的返回值的特性来做
1
2
3
4
5
6
7
8
9
10
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Set<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
if (i > k)set.remove(nums[i - k - 1]);//最多k个元素,超过k个元素就从头开始删除
if (!set.add(nums[i])) return true;//加不进去了,说明距离比k小
}
return false;
}
}