HashSet Java solution


  • 0
    J
    1. Find duplicates means abs(nums[j] – nums[i]) = 0
    2. The absolute difference between i and j is at most k means idx_j – idx_i <= k which implicitly indicate a window. The window is maintained by the size of HashSet

    inspired by contains duplicates III

    public class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            // corner case
            if (nums == null || nums.length <= 1) { return false;}
            // Set + window
            Set<Integer> set = new HashSet<>();
            for (int i = 0; i < nums.length; i++) {
                int num = nums[i];
                if (set.contains(num)) {
                    return true;
                } 
                set.add(num);
                // maintain window
                if (set.size() > k) {
                    set.remove(nums[i - k]);
                }
            }
            // return
            return false;
        }
    }
    

Log in to reply
 

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