Topic Analysis:
-
For all integers except one occurrence, the number of occurrences of each digit in the binary representation of 1 is an integer multiple of 3, all of these 1 are zeroed, and the remainder is the final number.
-
With ones recorded to the current calculated variable, the binary 1 appears "1 Times" (1 after mod 3) digits. With twos recorded to the current calculated variable, the binary 1 appears "2 times" (2 after mod 3) digits. When one of the ones and twos is 1, the binary 1 appears 3 times, which requires zeroing. Binary simulation is used to calculate the binary. The final ones record is the final result.
-
complexity of Time: O (N)
-
Example code:
int Singlenumber (int n) {for (return ones;}
Here's what I understand:
Ones for 1,a[i] 0 o'clock, ones unchanged, twos unchanged
Ones is 1,a[i] 1 o'clock, ones changes to 0,twos to 1
Ones for 0,a[i] 0 o'clock, ones unchanged, twos unchanged
Ones is 0,a[i] 1 o'clock, ones changes to 1,twos unchanged
Twos changes only ones and a[i] are 1 o'clock, so twos |= (ones & A[i]) can be understood
It is not difficult to see the origin of ones ^= A[i]
After that, ones and twos were 1, and they zeroed out.
The following extensions are mentioned on a Web site:
Extension one:
Given an array of n integers, all integers appear three times, except for a number that occurs two times, to find the integer that appears only two times. Ones record 1 appears once the number, twos record 1 appears 2 times the number, easy to know twos record is the final result.
Extension two:
Given an array of n integers, an integer x appears b, an integer y appears c, and all the other numbers appear a, where B and C are not multiples of a, finding X and Y. Using binary analog A, the cumulative number of bits 1 occurrences, when the number of times reached a, the zero, so that the B mod a x,c mod a y cumulative. Traverse the remaining results (with ones, twos, fours ... Variable representation of each bits 1 occurrences, if the number of times is B mod A or C mod A, you can explain the X and y of the current bits is different (one is 0, the other is 1), according to bits the original array into two groups, one group of the BITS is 1, the other set of bits is 0. The problem becomes "A-time" for all integers except an integer occurrence a1 (a1 = B or a1 = C), and the final result can be obtained using the same calculation as above, assuming that the variables used in the simulation of the A-binary calculation are ones, twos, fours ... Then the final result can be used ones | Twos | Fours ... Said.
Reference URL:
http://www.tuicool.com/articles/UjQV7n
Single number II