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.
Example:
Input:[1,2,1,3,2,5]
Output:[3,5]
Note:
- The order of the result is not important. So in the above example,
[5, 3]
is also correct. - Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
给定一个数组,其中有两个数只出现了一次,其他的数都出现了两次,求出这两个数。
这道题在面试时遇到,当时只能想到用一次异或求出出现不同的数和借助set来找出该数。后来面试官提示,异或为1代表该位两个数不相同,这样就可以将两个数分开。当时一知半解,故特写博客一篇作为记录。
正如我们所知,一次异或操作得到的值为要求的两数的异或值。由于存在两不同的数,因此该异或值一定不为0,对于该异或值中不为1的那一位,说明可以将数组分成两部分,一部分为数组该位值为1的,另一部分该位值为0,代码如下:
vector<int> singleNumber(vector<int>& nums) {
if (nums.size() < 2)return vector<int>();
else if (nums.size() == 2)return nums;
int all = 0;
for (auto num:nums)
all ^= num;
int flag = 0x01;
while (true) {
if (flag & all)break;
flag <<= 1;
}
int res1 = 0, res2 = 0;
for (auto num : nums) {
if (num & flag)
res1 ^= num;
else res2 ^= num;
}
vector<int> result;
result.push_back(res1);
result.push_back(res2);
return result;
}