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:
[5, 3] is also correct.思路:对所有数进行一次异或运算。运算结果为所求的两个数的异或结果。
因为两个数是不同的,因此结果必不为0。设该结果为res,其二进制形式必有几位是1。而根据异或运算规则,所求的两个数在这些位上一定有一个是1,一个是0。我们从这些位中随便取1位,然后将所有的数根据在这一位上是0还是1分成两组。则所求的两个数必然分别在这两个组内,此时分别再进行一次异或运算,就得到了两个数。
代码中 res随机取二进制为1的一位 用的是 res &= -res; 目前没完全搞懂为什么这样就必然对,暂且先记住。
此外,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 };
原文:http://www.cnblogs.com/fenshen371/p/4908206.html