yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #260 Single Number III #184

Open yokostan opened 5 years ago

yokostan commented 5 years ago
class Solution {
    public int[] singleNumber(int[] nums) {
    int result[] = new int[2];        
    int xor = nums[0];
    for (int i=1; i<nums.length; i++)
    {
        xor ^= nums[i];
    }

    int bit = xor & ~(xor-1);
    int num1 = 0;
    int num2 = 0;

    for (int num : nums)
    {
        if ((num & bit) > 0)
        {
            num1 ^= num;
        }
        else
        {
            num2 ^= num;
        }
    }

    result[0] = num1;
    result[1] = num2;
    return result;
    }
}

Amazing explanation: We're sub-grouping the numbers as ith digit is either 0 or 1. https://leetcode.com/problems/single-number-iii/discuss/68901/Sharing-explanation-of-the-solution