Total Accepted: 14412
Total Submissions: 36361
Difficulty: Medium
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:
- 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?
Hide Tags
Hide Similar Problems
找出数组中两个唯一出现一次的数;
解题思路:(假设这个两个数是a和b)
1.XOR异或所以元素,求出axb = a ^ b;
2.求出axb中的最后一位1,lastBit = -axb & axb,求法参考文章“位操作实现加减乘除四则运算”。
3.用这一位lastBit来分组:如果lastBit & nums[i] == 1,a ^= nums[i],遍历完后,结果即为a。
4.b = a ^ axb。
代码如下:
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int axb = nums[0];
for(int i=1;i<nums.size();i++) axb ^= nums[i];
int lowestOneBit = -axb & axb;
int a = 0;
for(int i=0;i<nums.size();i++)
{
if(lowestOneBit & nums[i]) a ^= nums[i];
}
int b = a ^ axb;
nums.clear();
nums.push_back(a);
nums.push_back(b);
return nums;
}
};