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.
給定數(shù)組nums,求里面重復(fù)元素的距離是否最大不超過k。
Solution:
利用HashMap來存nums[i]與其對應(yīng)的index i,這里要注意HashMap里面的更新問題,如果多次重復(fù)出現(xiàn)某個元素,則HashMap里面更新為最新的該元素與index的映射關(guān)系,可能滿足距離小于等于k的兩個nums[i]元素只可能是當(dāng)前這個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;
}
}