类似题参考LeetCode169
以及次数超过1/3的数字 LeetCode 229
思路1:时间复杂度O(nlogn)
排序完以后直接取最中间的那个数,因为该数字超过了一半
思路二:投票法。时间复杂度O(n) 空间复杂度O(1)
# -*- coding:utf-8 -*-
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
count , candi = 0 , 0
for i in numbers:
if candi == i:
count += 1
else:
if count == 0:
candi , count = i , 1
else:
count -= 1
return candi if numbers.count(candi)>len(numbers)/2 else 0
最详细的思路 参考自己博客 求众数