Sliding Window JAVA Solution


  • 0
    C
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            Set<Integer> set = new HashSet<>();
            int curr = 0;
            int length = nums.length;
            while (set.size() < k && curr < length) {
                if (set.contains(nums[curr])) return true;
                else set.add(nums[curr]);
                curr++;
            }
            int front = 0;
            while (curr < length) {
                if (set.contains(nums[curr])) return true;
                else {
                    set.add(nums[curr]);
                    set.remove(nums[front]);
                    front++;
                    curr++;
                }
            }
            return false;
    }
    

    Build a slide window to store the first k objects (if applicable), and remove a front object and add a new object in the set. Space: O(k), Time: O(n).


  • 0
    C

    This is good. It is a tradeoff between space and time.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.