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,当且仅当存在两个不同的下标i和j满足nums[i] = nums[j]并且|i-j|<=k时返回true,否则返回false。
思路:遍历数组中每个元素,将(muns[i], i)存入一个map中。如果键nums[k]已经存在,则比较之前的索引和当前的索引的差值,如果差值不大于k,说明到了满足条件的两个值,否则使用新的索引作为值 。
public class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { if(nums==null||nums.length<2||k<1) return false; Map<Integer,Integer> map = new HashMap<>(); for(int i=0;i<nums.length;i++){ if(!map.containsKey(nums[i])){ map.put(nums[i],i); }else{ int index=map.get(nums[i]); if(i-index<=k){ return true; } map.put(nums[i],i); } } return false; } }