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.
给定一个整型数组和一个整数k,判断数组内是否包含两个相同的数,且这两个数的下标差的绝对值不大于k
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashMap<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++){
int index=map.getOrDefault(nums[i],-1);
if(index==-1||Math.abs(index-i)>k){
map.put(nums[i],i);
}
else{
return true;
}
}
return false;
}
}