[JAVA] XOR all and differentiate by using 1 bit. / T : O(N), S : O(1)


  • 0
    J
    public class Solution {
        public int[] singleNumber(int[] nums) {
            int[] result = new int[2];
            int sum = 0;
            for(int num : nums){
                sum ^= num;
            }
            
            // 101000 ^ (011000)
            int rightbit = sum & ~(sum - 1);
            for(int num : nums){
                if((rightbit & num) == 0){
                    result[0] ^= num;
                }
                else{
                    result[1] ^= num;
                }
            }         
                
            
            return result;
        }
    }
    

Log in to reply
 

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