Java Solution beats 99.8%, easy to understand, no data structures


  • 0
    M

    I used two pointers instead of a hashmap, and this solution beats 99.8% of Java solutions. Hope it helps!

    public boolean containsNearbyDuplicate(int[] nums, int k) {
        if (k <= 0 || nums.length < 2) return false;
        int left = 0, right = 1;
        while (right < nums.length) {
            if (left != right && nums[left] == nums[right]) return true;
            int diff = right - left;
            if (diff == k) {
                left++;
            } else {
                right++;
            }
        }
        while (left < right-1) {
            if (nums[left++] == nums[right-1]) return true;
        }
        return false;
    }

  • 0
    G

    This solution is incorrect, even it can pass all the test cases.
    When you have your left pointer increased to narrow down the window, if k is larger than 2, you'll miss the comparison between nums[left] and nums[left+1].

    Try this example below:

    [1,2,2,3,4,5]
    3
    

    Your output is false, while correct should be true


Log in to reply
 

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