Java solution in 3 lines, O(n) and without extra space


  • 8
    H

    A simple solution, using 2 properties of XOR: A ⊕ A = 0 and B ⊕ 0 = B
    In other words, A ⊕ A ⊕ B = B

    public int singleNumber(int[] nums) {
      for(int i=0;i<nums.length-1;i++){
        nums[i+1] ^= nums[i];
      }
      return nums[nums.length-1];
    }

  • 0
    L

    @hillol Good explanation and neat code.


Log in to reply
 

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