leetcode 219. Contains Duplicate II

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;
    }
}
posted on 2019-04-07 22:55  王 帅  阅读(86)  评论(0编辑  收藏  举报