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].

一个数组里存在两个只出现一次的数字,其余的均出现两次,找出那两个数。

对于找出只出现一次的数字,用异或最简单,但是这里有两个,显然全体数组一起异或是不行的。

所以要分组异或,分组的目的是把两个数分别放到两个子数组中,这样异或后的值就是答案。

关键是如何分组,考虑到两个不同的数必然有一位数字不同,假设是第r位不同,那么就可以把第r位是1的分为一组,其余的另成一组,这样两个数字必然在两个组。

接下来是如何找到那个r,解决办法就是全体异或一遍,找到一个值为1的位就可以了。

 1 class Solution {
 2 public:
 3     vector<int> singleNumber(vector<int>& nums) {
 4         vector<int> res;
 5         if( nums.empty() )
 6             return res;
 7         int k = nums[0];
 8         for( int i=1; i<nums.size(); i++ ){
 9             k = k ^ nums[i];
10         }
11         int temp = 1;
12         while( (temp & k) != temp )
13             temp = temp << 1;
14         
15         vector<int> res1;
16         vector<int> res2;
17         for( int i=0; i<nums.size(); i++ ){
18             if( (nums[i] & temp)==temp )
19                 res1.push_back(nums[i]);
20             else
21                 res2.push_back(nums[i]);
22         }
23         for( int i=1; i<res1.size(); i++ ){
24             res1[0] = res1[0] ^ res1[i];
25         }
26         res.push_back( res1[0] );
27         for( int i=1; i<res2.size(); i++ ){
28             res2[0] = res2[0] ^ res2[i];
29         }
30         res.push_back( res2[0] );
31         
32         return res;
33     }
34 };

 

posted @ 2018-03-23 19:23  Zzz...y  阅读(285)  评论(0编辑  收藏  举报