260. Single Number III

这题又烦了我好几天…………

https://discuss.leetcode.com/topic/21605/accepted-c-java-o-n-time-o-1-space-easy-solution-with-detail-explanations

这个朋友的想法太厉害啦

方法:

1. 第一个pass: 把数组里面所有的数都xor起来,会得到单独的两个数的xor结果:

  1)相同的元素xor结果是0,和0 xor的结果是这个数本身

  2)因为单独的两个数彼此之间是不相同的,所以一定有一些数位上的数是不同的,xor的结果这位上就是1.

    xor = ~(xor - 1) 能够找到两个数里面最右的一个不同的数位

2. 第二个pass:对于数组里面的所有的数,和那个最右不同的数位xor,不同的那两个单独的数一定会被分到不同的组,然后对两个组内部再xor一次,就能得到结果

  1)如果结果是0,也就是说这一位上是设置了的那个,和res[0] xor

  2) 否则, 和res[1] xor

返回结果

 

 1     public int[] singleNumber(int[] nums) {
 2         int xor = 0;
 3         for(int num : nums) {
 4             xor ^= num;
 5         }
 6         xor &= ~(xor - 1);
 7         int[] res = new int[2];
 8         for(int num: nums) {
 9             if((num & xor) == 0) {
10                 res[0] ^= num;
11             } else {
12                 res[1] ^= num;
13             }
14         }
15         return res;
16     }

 

posted @ 2016-08-19 03:04  warmland  阅读(127)  评论(0编辑  收藏  举报