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.
My original solution using a HashMap:
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for(int i=0;i<nums.length;i++){
if(map.containsKey(nums[i])){
if(i-map.get(nums[i])>k) map.put(nums[i],i);
else return true;
}else map.put(nums[i],i);
}
return false;
}
}
However, in the discuss, sbdy suggest that using set has better performance.
public boolean containsNearbyDuplicate(int[] nums, int k) {
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < nums.length; i++){
if(i > k) set.remove(nums[i-k-1]);
if(!set.add(nums[i])) return true;
// cannot add into the set, duplicates found
}
return false;
// no duplicates found
}
Explanation:
It iterates over the array using a sliding window.
The front of the window is at i, the rear of the window is k steps back.
The elements within that window are maintained using a set.
While adding new element to the set, if add() returns false, it means the element already exists in the set.
At that point, we return true.
set.add() returns a boolean type -> slight performance improvement avoid using set.contains()
So is set preferred over a map? Not actually.. Maybe its the Map.containsKey() method that costs more time.