Java AC solution with Sliding Window 3ms


  • 1
    N

    The basic idea is to scan every pair of elements within the window size. So I didn't need the help of a set. Need to be careful about some edge cases. I got 3ms overall. New to the discussion board, welcome any comment (。・ω・。)

    public class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            if (nums == null || nums.length == 0 || k == 0) {
                return false;
            }
            for (int i = 0, j = 1; j < nums.length; j++) {
                if (j - i <= k && nums[i] == nums[j]) {
                    return true;
                }
                if (j - i > k || j == nums.length - 1) {
                    while (i < j - 1) {
                        i++;
                        if (nums[i] == nums[j]) {
                            return true;
                        }
                    }
                }
            }
            return false;
        }
    }
    

  • 0
    U

    Your answer is wrong, although you pass all test case.

    Please try this test case:
    [2,5,5,4,6]
    3
    You got false but the system expected true!


Log in to reply
 

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