Question
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 j is at most k.
Solution -- HashMap
1 public class Solution { 2 public boolean containsNearbyDuplicate(int[] nums, int k) { 3 int length = nums.length; 4 if (length <= 1 || k < 1) 5 return false; 6 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 7 int min = Integer.MAX_VALUE; 8 for (int i = 0; i < length; i++) { 9 if (map.containsKey(nums[i])) { 10 int prev = map.get(nums[i]); 11 int gap = i - prev; 12 min = Math.min(min, gap); 13 } 14 map.put(nums[i], i); 15 } 16 if (min <= k) 17 return true; 18 else 19 return false; 20 } 21 }