Single number III
Given An array of numbers nums
, in which exactly-elements appear only once and all the other elements appear exactly Twice. 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, is
[5, 3]
also correct.
- Your algorithm should run in linear runtime complexity. Could implement it using only constant space complexity?
Credits:
Special thanks to @jianchao. Li.fighter for adding the problem and creating all test cases.
The main question is how to separate A and B of two only one number.
If all the different or words get the result is a^b.
A! =b, so the XOR result must exist 1, then 1 of the corresponding A and B must be 1, one is 0, this can divide all the numbers into two categories.
Two values can be achieved respectively.
The method to get the last different bit of a, B is Mask=axorb & (~axorb-1)).
1 classSolution {2 Public:3vector<int> Singlenumber (vector<int>&nums) {4vector<int>result;5 if(Nums.size () <2)returnresult;6 intAxorb =0;7 for(intI=0; I<nums.size (); i++)8 {9axorb^=Nums[i];Ten } One intMask = Axorb & (axorb-1)); A intA=0, b=0; - for(intI=0; I<nums.size (); i++) - { the if(mask&Nums[i]) - { -a^=Nums[i]; - } + Else - { +b^=Nums[i]; A } at } - Result.push_back (A); - Result.push_back (B); - returnresult; - } -};
[Leetcode] Single number III