lc169.多数元素

 

题目链接

此题与jz039.数组中出现次数超过一半的数字相同。这个算法的时间复杂度是O(N),空间复杂度是O(N)。

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        votes = 0
        for num in nums:
            if votes == 0:
                x = num
            if x == num:
                votes += 1
            else:
                votes -= 1
        return x