Given an array of integers, every element appears three times except for one. Find the single one.
Note:
Your algorithm should has a linear runtime complexity. Could you implement it without using extra memory?
Ideas:
Consider all binary representations, if we take the sum of all the numbers on the first th position and the 3, then there will only be two results 0 or 1 (according to test instructions, 3 0 or 3 1 Add the remainder to 0). So the result of the remainder is that "single number".
A straightforward implementation is to use an array of size 32 to record the and on all bits.
intSinglenumber (intA[],intN) {intCOUNT[32] = {0}; intresult = 0; for(inti = 0; I < 32; i++) { for(intj = 0; J < N; J + +) { if((A[j] >> i) & 1) {Count[i]++; }} result|= ((Count[i]% 3) <<i); } returnresult;}
Improved:
This algorithm has improved space and can be used with mask variables:
ones
Mask variable that represents only one occurrence of the first th bit
twos
Mask variable representing only two occurrences of the first th bit
Assuming that there are 3 consecutive 5 occurrences at the beginning of the array, the change is as follows:
ones = 101twos = 0--------------ones = 0twos = 101--------------ones = 0twos = 0--------------
When the first th bit appears 3 times, we set the ones
first twos
th bit to 0. The final answer is ones.
The code is as follows:
Public intSinglenumber (int[] A) {intone = 0; intboth = 0; inttmp; for(inti=0; i<a.length; i++) {= (A[i] & one) |both ; One= one ^A[i]; TMP= ~ (One &); One= one &tmp; both= &tmp; } returnOne ; }
The above analysis section references the self-propelled cool: http://www.tuicool.com/articles/fAZZv2a
LeetCode-137 Single number II