Moore's voting algorithm in Python (O(n))

  • 4
    class Solution(object):
    def majorityElement(self, nums):
        # implement the Moore's voting algorithm: find a pair different element and delete it
        count = 0
        for i in range(0, len(nums)):
            if count == 0:
                key = nums[i]
                count = 1
                if key == nums[i]:
                    count += 1
                    count -= 1
        return key

Log in to reply

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