
题目
Boyer-Moore 算投票算法:
我们维护一个候选众数 candidate 和它出现的次数 count。初始时 candidate 可以为任意值,count 为 0;
我们遍历数组 nums 中的所有元素,对于每个元素 x,在判断 x 之前,如果 count 的值为 0,我们先将 x 的值赋予 candidate,随后我们判断 x:
如果 x 与 candidate 相等,那么计数器 count 的值增加 1;
如果 x 与 candidate 不等,那么计数器 count 的值减少 1。
在遍历完成后,candidate 即为整个数组的众数。
class Solution:
    def majorityElement(self, nums):
        count = 0
        candidate = 0
        for n in nums:
            if count==0:
                candidate = n
            if candidate==n:
                count += 1
            else:
                count -= 1
        return candidate