Two Python Solutions with O(N) time and O(1) space


  • -1
    U
    class Solution(object):
        def singleNumber(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            one = 0
            second = 0
            for num in nums:
                one = (one ^ num) & ~second
                second = (second ^ num) & ~one
                
            return one
        
        def singleNumber(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            ans = 0
            nums = map(lambda x: x & 0xffffffff, nums)
            for index in range(32):
                bit = 0
                for num in nums:
                    bit += (num & (1 << index)) != 0
                
                ans |= ((bit % 3) << index)
                if index == 31 and (ans & (1 << 31)) != 0:
                    ans |= (-1 << 31)
            
            return ans | (-1 << 31) if (ans & (1 << 31)) != 0 else ans
            
    

  • 0
    C

    could you give some explanation?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.