1.题目
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].
2.分析
剑指offer中也有这道题,剑指offer: 数组中只出现一次的数字
3.代码
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int tmp = 0;
for (int x : nums)
tmp ^= x;
int bit = 1;
while (!(tmp&bit))
bit <<= 1;
int a = 0;
int b = 0;
for (int x : nums) {
if (x&bit)
a ^= x;
else
b ^= x;
}
return vector<int>{a, b};
}
};