260. 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:

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

含义:给定的数组中两个元素各出现了一次,其余元素都出现了两次,找出这两个元素

思路:首先我们先把原数组全部异或起来,那么我们会得到一个数字,这个数字是两个不相同的数字异或的结果,我们取出其中任意一位为‘1’的位,为了方便起见,我们用 a &= -a 来取出最右端为‘1’的位,然后和原数组中的数字挨个相与,那么我们要求的两个不同的数字就被分到了两个小组中,分别将两个小组中的数字都异或起来,就可以得到最终结果了

 1     public int[] singleNumber(int[] nums) {
 2 //        http://www.cnblogs.com/grandyang/p/4741122.html
 3 //        有两个数字都只出现了一次,那么我们如果能想办法把原数组分为两个小数组,不相同的两个数字分别在两个小数组中,
 4 //        这样分别调用Single Number 单独的数字的解法就可以得到答案。那么如何实现呢,首先我们先把原数组全部异或起来,那么我们会得到一个数字,
 5 //        这个数字是两个不相同的数字异或的结果,我们取出其中任意一位为‘1’的位,为了方便起见,我们用 a &= -a 来取出最右端为‘1’的位,
 6 //        然后和原数组中的数字挨个相与,那么我们要求的两个不同的数字就被分到了两个小组中,分别将两个小组中的数字都异或起来,就可以得到最终结果了
 7         int a = 0;
 8         for (int num : nums) {
 9             a ^= num;
10         }
11         // 取出第一位bit1     a & (~ (a - 1))
12         //取出最后一位bit1    a &= -a
13         int bitFlag = (a &= -a);
14         int[] res = new int[2];
15         for (int num : nums) {
16             if ((num & bitFlag) == 0) {
17                 res[0] ^= num;
18             } else {
19                 res[1] ^= num;
20             }
21         }
22         return res; 
23     }
原文地址:https://www.cnblogs.com/wzj4858/p/7728057.html