出现次数超过了一半,那就用一个count计数,相等加1,不等减1,count<0就更换res class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ res=nums[0] count = 0 for num in nums: if res == num: count +=1 else: count -=1 if count < 0: res = num count = 1 return res