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;
}
}