LeetCode 137 appear only once digital II

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 3xor 3x + 1, after %3after the completion of the de-emphasis of work


Whereby the meaning of problems become, by bit operations design 加法器and %3operation of the digital circuit

Since the maximum number is 3at least required 2bitto 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 _ (: з "∠) _

0

method one

1

Method Two

2

Method Three

Since the anderivation is substantially the same, to name only a anderived 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;
}

Guess you like

Origin www.cnblogs.com/Simon-X/p/11415644.html