卖萌的弱渣

I am stupid, I am hungry.

Single Number 2

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

(Single-Number2.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """

        # "1" appear once
        t1 = 0
        # "1" appear twice
        t2 = 0
        # "1" appear three times
        t3 = 0

        for i in nums:
            # update t2
            t2 |= t1 & i
            # update t1
            t1 = t1 ^ i
            # check which bits appear three times
            t3 = (t1 & t2)

            # put those bits to 0
            t1 &= ~t3
            t2 &= ~t3
        return t1