leetcode 原题链接:https://leetcode.com/problems/single-number-iii/
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?
<span style="font-size:14px;">class Solution
{
public:
vector<int> singleNumber(vector<int>& nums)
{
int target = 0x0;
for (int i = 0; i < nums.size(); i++)
{
target ^= nums[i];
}
int div = 0x1;
while ((div & target) == 0)
{
//cout << "div = " << div << endl;
div <<= 1;
}
//cout << "div = " << div << endl;
int n = 0x0, m = 0x0;
for (int i = 0; i < nums.size(); i++)
{
if ((div & nums[i]) == 0)
{
//cout << "n " << nums[i] << endl;
n ^= nums[i];
} else
{
//cout << "m " << nums[i] << endl;
m ^= nums[i];
}
}
vector<int> vec;
vec.push_back(n);
vec.push_back(m);
return vec;
}
};</span>