1 题目描述
2 解题思路
因为是O(N)的时间复杂度和O(1)的空间复杂度,所以想到的是Boyer-Moore 投票算法。这个算法的原理可见:算法整理:Boyer-Moore 投票算法_刘文巾的博客-CSDN博客
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
candidate=-1
count=0
for i in nums:
if(count==0):
candidate=i
if(candidate==i):
count+=1
else:
count-=1
#Boyer-Moore 投票算法
if(nums.count(candidate)>len(nums)//2):
return candidate
else:
return -1
#判断剩下的这个数是不是数量超过一半的那个数