Python AC Solution


  • 0
    T
    class Solution:
    # @param {integer[]} nums
    # @return {integer[]}
    def majorityElement(self, nums):
        n1, n2 = 0, 1
        c1 = c2 = 0
        for n in nums:
            if n == n1:
                c1 += 1
            elif n == n2:
                c2 += 1
            else:
                c1 -= 1
                c2 -= 1
            if c1 < 0:
                n1 = n
                c1 = 1
            elif c2 < 0 and n1 != n:
                n2 = n
                c2 = 1
        return [n for n in (n1, n2) if nums.count(n) > len(nums) // 3]

  • 0
    Z

    This solution cannot pass OJ now


  • 0

    It works on my machine. Rather than coping and pasting the code directly, indent the main function and its corresponding code maybe helpful.


Log in to reply
 

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