Boyer-Moore Majority Vote algorithm with Python's syntax sugar

  • 0

    This code was inspired by @orbuluh's Python implementation of Boyer-Moore Majority Vote algorithm in here, but used Python's syntax sugars to avoid duplicated if and elif blocks.

    class Solution(object):
        def majorityElement(self, numbers):
            counts = [0, 0]
            things = [0, 0]
            for number in numbers:
                if number in things:
                    counts[things.index(number)] += 1
                elif 0 in counts:
                    things[counts.index(0)] = number
                    counts[counts.index(0)] = 1
                    counts[:] = [count - 1 for count in counts]
            return [thing for thing in set(things)
                    if numbers.count(thing) > len(numbers) // 3]

Log in to reply

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