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 iand j is
at most k.
Java:
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashMap<Integer, Integer> hashmap = new HashMap<Integer,Integer>();
for(int i=0; i<nums.length; i++)
{
if(hashmap.containsKey(nums[i]))
{
if(i-hashmap.get(nums[i]) <= k) return true;
else hashmap.put(nums[i],i); //replace the old j value
}else
{
hashmap.put(nums[i],i);
}
}
return false;
}
}