Problem Description:
https://leetcode.com/problems/single-number-iii/
In an array, only two elements appear only 1 times, and the rest appear two times. Find out only those two that appear once (A, b).
Constant space, linear time is required.
Problem solving:
This problem uses "magical bit arithmetic".
1. Because in addition to the special two elements, the remaining 22 appears, then the idea of XOR (XOR).
2. After XOR from beginning to end, a XOR B result is obtained. Next we try to separate the two elements.
3. We find any one xor[diff_pos] = 1 in a XOR B, then we know that A and B are not the same on Diff_pos. If you follow Diff_pos, this value
Categories can divide all the numbers into two groups: 1) diff_pos = 0 elements, 2) Diff_pos = 1 elements.
4. For the two groups in the 3 group XOR, because the remaining elements are 22 appear, then finally left A/b.
The code is as follows:
classsolution (object):defSinglenumber (Self, nums): Xor=0 forNuminchNums:xor= xor^Num Diff_pos=0 forIinchRange (31): if(Xor & (1 <<i)): Diff_pos=I BreakRec=[0,0] forNuminchNums:if(Num & (1 <<diff_pos)): rec[1] ^=NumElse: rec[0]^=NumreturnRec
The paper has not yet looked, again in the blind engage ...
"Leetcode"--260. Single number III