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.

 

与217类似,就是多加了一个要求i和j距离最远是k。
 
1、HashMap最直接。
public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap();
        for (int i = 0; i < nums.length; i++){
            if (map.containsKey(nums[i])){
                if (i - map.get(nums[i]) <= k){
                    return true;
                }
            } 
            map.put(nums[i], i);
        }
        return false;
    }
}

 

 2、用HashSet也可以,用窗口的想法来实现。
public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        HashSet<Integer> set = new HashSet();
        for (int i = 0; i <= k && i < nums.length; i++){
            if (set.contains(nums[i])){
                return true;
            }
            set.add(nums[i]);
        }
        for (int i = k + 1, j = 0; i < nums.length; i++, j++){
            set.remove(nums[j]);
            if (set.contains(nums[i])){
                return true;
            }
            set.add(nums[i]);
        }
        return false;
    }
}

 

可以对上面的代码简化一下。