Keep a window of width k, before visit new element, remove nums[i - k - 1].
Other details are much the same as Contains Duplicate.

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Set<Integer> s = new HashSet<Integer>();
        int N = nums.length;
        for (int i = 0; i < N; ++i) {
            if (i - k - 1 >= 0) s.remove(nums[i - k - 1]);
            if (!s.add(nums[i])) return true;
        }
        return false;
    }
}
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。