Single Number III - LeetCode

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?

思路:对所有数进行一次异或运算。运算结果为所求的两个数的异或结果。

因为两个数是不同的,因此结果必不为0。设该结果为res,其二进制形式必有几位是1。而根据异或运算规则,所求的两个数在这些位上一定有一个是1,一个是0。我们从这些位中随便取1位,然后将所有的数根据在这一位上是0还是1分成两组。则所求的两个数必然分别在这两个组内,此时分别再进行一次异或运算,就得到了两个数。

代码中 res随机取二进制为1的一位 用的是 res &= -res; 

可以这样做的原因是,一个数的负为它的反码加1, 如数00100100,反码是11011011,将其加一后变为11011100,可以看到,原数最右的一个1现在仍然是1,其他位与运算完后是0。这样两数与运算后结果为00000100,即只有最右的一个1。

此外,for (:)的写法也是第一次见。

 1 class Solution {
 2 public:
 3     vector<int> singleNumber(vector<int>& nums) {
 4         int res = 0;
 5         for (int num : nums)
 6             res ^= num;
 7         res &= -res;
 8         vector<int> ans = {0, 0};
 9         for (int num : nums)
10         {
11             if (res & num)
12                 ans[0] ^= num;
13             else ans[1] ^= num;
14         }
15         return ans;
16     }
17 };

 

posted @ 2015-10-25 08:34  fenshen371  阅读(178)  评论(0编辑  收藏  举报