Given an array of integers and an integer k, find out whether there 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.
A:
就是简单的,在 k+1的长度中查询 duplicate
public 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 - 1 >=0) // delete first
set.remove( nums[i-k-1]);
if(set.contains(nums[i]))
return true;
set.add(nums[i]);
}
return false;
}
}
class Solution:
def containsNearbyDuplicate(self, nums: list[int], k: int) -> bool:
pos = {}
for i, val in enumerate(nums):
if val in pos and i - pos[val] <= k:
return True
pos[val] = i
return False
No comments:
Post a Comment