链接:https://leetcode.com/problems/single-number-iii/description/
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?
class Solution{
public:
vector<int> singleNumber(vector<int>& nums)
{
vector<int> res(2,0);
int mark=0;
for(auto num:nums)
mark^=num;
//The statement "int lowbit=mark&(~(mark-1));" can find the rightmost set bit. For
//example, for mark = 4, bit = 2, i.e., lowbit is
//"00000000000000000000000000000010" in binary format , the right first 1 in
//binary format
int lowbit=mark&(~(mark-1));
for(auto num:nums)
{
if((num&lowbit)==0)
res[0]^=num;
else
res[1]^=num;
}
return res;
}
};