ACWING74. The only appears only once in the array of numbers (to prove safety offer, state machine, binary)

In an array in addition to a number appears only once, other figures have appeared three times.

Find the number that appears only once.

You can assume that there must satisfy the conditions of numbers.

Questions:

If it requires only O (n) time and additional O (1) space, how to do it?
Sample
input: [1,1,1,2,2,2,3,4,4,4]

Output: 3

Reference: https: //leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-ii-lcof/solution/zhuang-tai-ji-jie-jue- ci-wen-ti-xiang-jie-shu-zi-d /

Had just finished writing the number of electrical work, it would face a circuit design problem here, really knowledge are interlinked ah. . . .

Ideas:
Solution one: all of the numbers, the statistics of the number of 1 bits each, if the number of mold 13, more than 1, then this bit is 1.

Solution two:
very clever, using the knowledge of the state machine. But this question, as long as know the circuit design (or bit operation) knowledge is enough.

May utilize two binary number: ab, it is used to represent the state of a ternary bit, a number representative of the value of I 3.

Initializing a = 0, b = 0.
the value 0: a = 0, b = 0
is 1: a = 1, b = 0
is 2: a = 0, b = 1

Suppose the value added c, c 0 is no input, c is 1 is input

As listed in a truth table
Here Insert Picture Description
of the truth table can be drawn
New_a = a'b'c '+ ab'c

For A:
new _a = B '(AC + a'c') = C & A ^ B '

For b:
In this case a transformation has taken place into a New_a.
Using the same New_a, b, c,
can be obtained:
B = New_a'bc 'New_a'b'c +
B = new _a' (B ^ C)

class Solution {
public:
    int findNumberAppearingOnce(vector<int>& nums) {
        int a = 0,b = 0;
        int n = nums.size();
        for(int i = 0;i < n;i++) {
            a = (a ^ nums[i]) & ~b;
            b = (b ^ nums[i]) & ~a;
        }
        return a;
    }
};

Simplification if not directly write the initial truth table a, b, c

class Solution {
public:
    int findNumberAppearingOnce(vector<int>& nums) {
        int a = 0,b = 0;
        int n = nums.size();
        for(int i = 0;i < n;i++) {
            int x = a;
            a = (x & ~b & ~nums[i]) | (~x & ~b & nums[i]);
            b = (~b & nums[i] & x) | (b & ~nums[i] & ~x);
        }
        return a;
    }
};

Published 843 original articles · won praise 28 · views 40000 +

Guess you like

Origin blog.csdn.net/tomjobs/article/details/105001697