Given An array of numbers nums, in which exactly, elements appear only once and all the other elements appear exactly t Wice. Find the 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. The above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could implement it using only constant space complexity problem solving skills:
This problem is similar to the single number, Numberii, and we can find a way to divide the two only occurrences into two different groups, and then call the method in the individual numbers to get the result. The practice is: first we can all the number of XOR, this will get two different number of differences or results, and then, X &=-X to remove the right end of the number a bit of 1, and then the number of the original array and operation, the two different numbers are divided into different groups, Finally, we can get the final result by making the difference or operation of the numbers in two groups.
Code:
#include <iostream>
#include <vector>
using namespace std;
int XOR (vector<int>& nums)
{
int sum = 0, Len = nums.size ();
for (int i = 0; i < len; i++)
{
sum = sum ^ nums[i];
}
return sum;
}
Vector<int> Singlenumber (vector<int>& nums) {
int diff;
diff = XOR (nums);
Diff &=-diff;
vector<int> Res (2, 0);
for (int i = 0; i < nums.size (); i++)
{
if (diff & Nums[i]) res[0] = Res[0] ^ nums[i];
else res[1] = res[1] ^ nums[i];
}
return res;
}
int main ()
{
vector<int> nums, res;
int x;
while (CIN >> x)
nums.push_back (x);
res = Singlenumber (nums);
for (int i = 0; i < res.size (); i++)
cout << res[i] << Endl;
System ("pause");
}