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 jis at most k.
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
int n = nums[i];
Integer index = map.get(n);
if (index != null && i - index <= k) {
return true;
}
map.put(n, i);
}
return false;
}
}
=========
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if (nums == null || nums.length == 0 || k == 0) {
return false;
}
HashSet<Integer> set = new HashSet<Integer>();
for (int i = 0; i <= 0 + k && i < nums.length; i++) {
if (set.contains(nums[i])) return true;
set.add(nums[i]);
}
for (int i = k + 1; i < nums.length; i++) {
set.remove(nums[i - 1 - k]);
if (set.contains(nums[i])) return true;
set.add(nums[i]);
}
return false;
}
}
没有评论:
发表评论