260. Single NumberIII

302 查看

题目:
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:
The order of the result is not important. So in the above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

解答:
只能用厉害来形容了!思路是第一个loop找到两个single number的一个同一位不同的bit;第二个loop是通过这bit把所以数分成两个group,因为其它数都是有两个,所以在这两组中,只是这两个数是单一的。再用以后就可以分别求出这两个数了。

public int[] singleNumber(int[] nums) {
    int diff = 0;
    for (int num : nums) {
        diff ^= num;
    }
    //我们有了这两个数不同的bit
    int[] result = new int[2];
    diff &= -diff;
    for (int num : nums) {
        if ((num & diff) == 0) {
            result[0] ^= num;
        } else {
            result[1] ^= num;
        }
    }
    return result;
}