using XOR and set the two integer into two groups


  • 1
    Y
    public class Solution {
        public int[] singleNumber(int[] nums) {
            int res[] = new int[2];
            int xor = 0;
            
            for (int i = 0; i < nums.length; i++) {
                xor ^= nums[i];
            }
            
            int rightRes = xor & (~(xor - 1));
            
            int group1 = 0, group2 = 0;
            for (int i = 0; i < nums.length; i++) {
                if ((rightRes & nums[i]) == 0) {
                    group1 ^= nums[i];
                } else {
                    group2 ^= nums[i];
                }
            }
            
            res[0] = group1;
            res[1] = group2;
            return res;
        }
    }
    

  • 0
    B

    take me sometime to get why should use the lower bit, the rightRes...


Log in to reply
 

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