LeetCode 137 appear only once digital II
Although not required to open up extra space and time complexity of O (n), and because the single data comparison water. Sorting was still able to rely on, so I spent some time thought
Digital de-emphasis, the time complexity of O (n) extra space and does not open, then on from the start bit computing
An element appears only once, each of the remaining three elements appear, put each split into binary numbers, after splitting the sum of every only 3x
or 3x + 1
, after %3
after the completion of the de-emphasis of work
Whereby the meaning of problems become, by bit operations design 加法器
and %3
operation of the digital circuit
Since the maximum number is 3
at least required 2bit
to achieve operational
Low number provided for the operation a
, is high b
, inputv
At the end of each calculation is low an
, as highbn
Bit arithmetic symbols used c language version
As for the specific design, it is free play
The following are readily schematic blind draw, did not follow any digital circuit diagram specifications _ (: з "∠) _
Since the an
derivation is substantially the same, to name only a an
derived part
FIG into equation
c = a ^ v
d = a & v
e = b | d
f = c ^ e
an = c & f
bn = e & f
an = c & f
= c & (c^e)
= c & (~e)
= c & (~(b|d))
= (a^v) & (~b) & (~d)
= (a^v) & (~b) & (~(a&v))
= (a^v) & (~b) & (a|v)
= (a^v) & (~b)
C
int singleNumber(int* nums, int numsSize){
int a = 0, b = 0;
for (int i = 0; i < numsSize; ++i) {
a = (a^nums[i]) & ~b;
b = (~a & nums[i]) ^ b;
}
return a;
}