LeetCode_Single Number II

Problem:

Single Number II

 

Given an array of integers, every element appears three times except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Solution:

1. Simplest solution is sort the array, find the one in an naive manner.

2. I thought about it for a while. Then Google the answer. The answer only contains a for loop, which is expected. 

And the content in the loop is a mass, which is not expected and can't be interpreted by my stupid mind. But the bit operation did give me a hint.

Also you have Single Number I in mind for reference. But for the solution for Single Number I, my interpretation is just that xor is commutative and two same numbers xor'ed is zero. All number xor'ed will result in the single target number.

But for Single Number II, how to eliminate the effects of three same numbers? The bit operations gives me the hint and remind me about logic design. Then I started to sketch a truth table like below.

B1 B0 Input B1` B0`
0 0 1 0 1
0 1 1 1 0
1 0 1 0 0
0 0 0 0 0
0 1 0 0 1
1 0 0 1 0

Then the straightforward transition function for B0 and B1 is as follows:

b1' = (!b1) b0 Inp + b1(!b0)(!inp);ie. bi` is 1 when b1b0Inp is 010 or 100.

b0` = (!b1) (!b0) Inp + (!b1) b0 (!Inp); ie. b0' is 1 when b1b0Inp is 001 or 010.

For b0` extract (!b1) then b0` = (!b1)  ( (!b0) Inp + b0 (!Inp) ) = (!b1) (b0^Inp);

So the code is as follows:

Code:

public class Solution {
    public int singleNumber(int[] A) {
        int b0 = 0;
        int b1 = 0;
        for(int i=0; i<A.length; i++){
            int b0t = (~b1)&(b0^A[i]);
            int b1t = (~b1)&b0&A[i]|b1&(~b0)&(~A[i]);
            b0 = b0t;
            b1 = b1t;
        }
        return b0;
    }
}


Extension:

To be a good programmer, you have to be a good problem solver and may have to borrow idea from other fields. Maybe that's why some recruitment requirements contains good problem solving ability. Programmer is programmer, not problem solver. Computer is just a tool. Someone says if you want to be good programmer, you have to know math. Maybe, that's putting the incidental before the fundamental. Know math is the fundamental, programming it on a computer is the incidental. Sometimes, innovation is just borrowing idea from other fields. So, think a lot about everything.

http://blog.csdn.net/cheetach119/article/details/12314037





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章