Leetcode: Single Number III

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?

Lintcode 也有这道题 Single Number III

example:

1 0 1 0 0 0

1 0 1 0 0 0

0 0 1 0 0 0

0 0 1 0 0 0

1 0 0 1 0 0

1 0 0 1 0 0

0 0 1 0 0 0

0 0 1 0 0 1

如例所示,最后两个数8,9即是所求Single Number, 即使它们能使某一位上的1凑成偶数(使得Single Number I 的方法不再有效)如上例从右到左第4位,但是始终会至少有某一位的1仍是奇数(如上例从右到左第一位)。

想法就是把这些数分成两拨,让这两个single number各在一拨,然后各自按Single Number I 的做法做,就可以找出来

取上述为1的各位中某一位,方便起见取最右边为1的那位,所有那位为1的数形成一拨,其余数形成另一拨,这样就把两个数分开到两拨了。各自XOR就可以得到两个数。

取最右边为1的那位的方法是:n & (-n)

Single Number I的一个简便方法是XOR各个数,如果某一位的1的个数是奇数,XOR之后仍将为1.

 1 public class Solution {
 2     public int[] singleNumber(int[] nums) {
 3         int[] res = new int[2];
 4         int n = 0;
 5         for (int elem : nums) {
 6             n ^= elem;
 7         }
 8         n = n & (-n);
 9         for (int elem : nums) {
10             if ((n & elem) == n) {
11                 res[0] ^= elem;
12             }
13             else res[1] ^= elem;
14         }
15         return res;
16     }
17 }
原文地址:https://www.cnblogs.com/EdwardLiu/p/5068743.html