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.
给定数组nums,求里面重复元素的距离是否最大不超过k。
Solution:
利用HashMap来存nums[i]与其对应的index i,这里要注意HashMap里面的更新问题,如果多次重复出现某个元素,则HashMap里面更新为最新的该元素与index的映射关系,可能满足距离小于等于k的两个nums[i]元素只可能是当前这个nums[i]和未来将要遍历到的nums[i]。
等价于求所有相邻的nums[i]之间是否存在有小于等于k的距离。
public class Solution
{
public boolean containsNearbyDuplicate(int[] nums, int k)
{
HashMap<Integer, Integer> hm = new HashMap<>();
for(int i = 0; i < nums.length; i ++)
{
if(hm.containsKey(nums[i]))
{
int preIndex = hm.get(nums[i]);
if(i - preIndex <= k)
return true;
}
hm.put(nums[i], i);
}
return false;
}
}