Easiest Java Solutions


  • 0
    B

    This solution looks at each pair starting from index 0 and returns the non duplicate (which should appear on an even index because duplicates can only be at most 2 elements).

    Runtime is O(log(n)) since the loop iterates over every other element

    public int singleNonDuplicate(int[] nums) {
            for (int i = 0; i < nums.length - 1; i+=2) {
                if (nums[i] != nums[i+1]) return nums[i];
            }
            
            // nums array must be odd and the non duplicate is at the very end missed by the loop
            return nums[nums.length - 1];
        }
    

  • 0
    A

    Your solution is O(n)


Log in to reply
 

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