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.

B1B0InputB1`B0`
00101
01110
10100
00000
01001
10010

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





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值