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?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
位运算,因为有两个元素不同,所以所有元素异或以后肯定不会为0,至少有一位为1。
找到第几位为一,异或操作分别找到两个数字
AC代码:
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
vector<int> res;
int sum=nums.size();
if(sum==0)
return res;
if(sum<=2)
return nums;
int temp=nums[0];
for(int i=1;i<sum;++i)
temp^=nums[i];
int count=0;
while(1)
{
if(temp&1==1)
break;
else
{
temp>>=1;
++count;
}
}
int res1=0;
int res2=0;
for(int i=0;i<sum;++i)
{
if((nums[i]>>count)&1==1)
res1^=nums[i];
else
res2^=nums[i];
}
res.push_back(res1);
res.push_back(res2);
return res;
}
};
其他Leetcode题目AC代码:https://github.com/PoughER/leetcode