Title Description:
/*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].
*/
The first solution was violent, sorted directly and then implemented with a stack:
classSolution { Public: Vector<int> Singlenumber (vector<int>&nums) {Stack<int>STA; Sort (Nums.begin (), Nums.end ()); for(inti =0; I < nums.size (); i++) { if(Sta.empty ()) {Sta.push (nums[i]); } Else { if(Sta.top () = =Nums[i]) {Sta.pop (); } Else{Sta.push (nums[i]); }}} vector<int>results; while(!Sta.empty ()) {Results.push_back (Sta.top ()); Sta.pop (); } returnresults; }};
And then looked at the puzzle, incredibly can use O (n) time complexity and O (1) space complexity.
The idea is that it needs to be divided into two steps:
1. All the numbers will be different or, we will get a diff, according to the nature of the difference or the same 0 1, then the occurrence of two times the difference or will become 0, we get the diff equivalent of two only 1 times the difference of the number of differences or values, the next step we need to put these two numbers a and b to find out, Because these two numbers are definitely different, then there will be certain bit XOR or after 1, according to diff, we can find any one of the diff in the 1 bit, to distinguish the two numbers, here we use the low in the first occurrence of the bit 1, in order to get this bit, you can use the diff &- Diff to find out, for example, diff = 6 (0110),-diff (1010), diff &-diff = (0110) & (1010) = 0010 is the 1 lowest, this bit can be used in the second section to distinguish between A and B, we can Use diff &=-diff to change the diff to this distinguished bit 0010
2. Next is to divide all the numbers into two groups according to the distinguishable, when nums[i] & diff = = 0 o'clock, divided into a group, when nums[i] & diff! = 0 o'clock is divided into another group, and finally we can determine that A and B these two values are definitely divided into two groups , in addition, we can optimize the place is that we can start to be in the group of different or, will be two times the number is offset, the final value is we want A and B
classSolution { Public: Vector<int> Singlenumber (vector<int>&nums) { intdiff =0; for(inti =0; I < nums.size (); i++) {diff^=Nums[i]; } diff&=-diff;//The one with the smallestvector<int> results = {0,0}; for(inti =0; I < nums.size (); i++) { if(Nums[i] &diff) {results[0] ^=Nums[i]; } Else{results[1] ^=Nums[i]; } } returnresults; }};
260. Single number III