Advertisement
1988coder

260. Single Number III

Jan 28th, 2019
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.30 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/single-number-iii/
  2.  
  3. /**
  4.  * Two Pass solution
  5.  *
  6.  * In the first pass, we XOR all elements in the array, and get the XOR of the
  7.  * two numbers we need to find. Note that since the two numbers are distinct, so
  8.  * there must be a set bit (that is, the bit with value '1') in the XOR result.
  9.  * Find out an arbitrary set bit (for example, the rightmost set bit).
  10.  *
  11.  * In the second pass, we find all numbers with the aforementioned bit set. XOR
  12.  * all filtered numbers. This will provide us first number. Second number can be
  13.  * found by XOR of this number and the original XOR value.
  14.  *
  15.  * Time Complexity: O(N) -> All numbers are visited twice.
  16.  *
  17.  * Space Complexity: O(1) -> Algorithm uses constant space.
  18.  *
  19.  * N = Length of the input array.
  20.  */
  21. class Solution {
  22.     public int[] singleNumber(int[] nums) {
  23.         if (nums == null || nums.length < 2) {
  24.             return new int[0];
  25.         }
  26.  
  27.         int aXORb = 0;
  28.         for (int num : nums) {
  29.             aXORb ^= num;
  30.         }
  31.  
  32.         int rightSetBit = aXORb & -aXORb;
  33.         int a = 0;
  34.         for (int num : nums) {
  35.             if ((num & rightSetBit) != 0) {
  36.                 a ^= num;
  37.             }
  38.         }
  39.  
  40.         int b = aXORb ^ a;
  41.  
  42.         return new int[] { a, b };
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement