LeetCode 137 [Single Number II]

weixin_34075551發表於2016-08-08

原題

給出3*n + 1 個的數字,除其中一個數字之外其他每個數字均出現三次,找到這個數字。

樣例
給出** [1,1,2,3,3,3,2,2,4,1]** ,返回 4

解題思路

  • 方法一:三進位制不進位加法,比如02 + 01 = 00 (2+1=3做加法不進位)。所以同一個數,比如7的三進製表示為21,21+21+21 = 00 即十進位制下的0。最終程式碼即統計每一位上1,對3取模
  • 方法二:分別統計,記錄出現一次,兩次,三次的數

完整程式碼

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        ones, twos, threes = 0, 0, 0
        for item in A:
            twos |= ones & item      
            ones ^= item          
            threes = ones & twos     

            ones ^= threes         
            twos ^= threes         
        return ones

相關文章