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?

 

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

 1 class Solution {
 2 public:
 3   int FindFirstBit(int num)
 4     {
 5         int index = 0;
 6         while (((num & 1) == 0) && (index < 8 * sizeof(int)))
 7         {
 8             num = num >> 1;
 9             ++index;
10         }
11         return index;
12     }
13     bool IsBit(int num, int index)
14     {
15         num = num >> index;
16         return (num & 1);
17     }
18     vector<int> singleNumber(vector<int>& nums) {
19         int sum = nums[0];
20         for (int i = 1;i < nums.size();i++)
21         {
22             sum ^= nums[i];
23         }
24         int f = FindFirstBit(sum);
25         vector<int> vet1;
26         vector<int> vet2;
27         for (int i = 0;i < nums.size();i++)
28         {
29             if (IsBit(nums[i], f))
30                 vet1.push_back(nums[i]);
31             else
32             {
33                 vet2.push_back(nums[i]);
34             }
35         }
36         int sum1 = vet1[0];
37         for (int i = 1;i < vet1.size();i++)
38         {
39             sum1 ^= vet1[i];
40         }
41         int sum2 = vet2[0];
42         for (int i = 1;i < vet2.size();i++)
43         {
44             sum2 ^= vet2[i];
45         }
46         vector<int> vet3;
47         vet3.push_back(sum1);
48         vet3.push_back(sum2);
49         return vet3;
50     }
51 };

 

posted on 2017-09-03 19:49  无惧风云  阅读(121)  评论(0编辑  收藏  举报