- 创建dict,遍历一遍数组,将每个值出现的次数统计一遍,再找出统计量最大的值;
- 直接对数组排序,取排序后的中间值;
- 求众数,若cnt=0,取当前值为众数,若cnt>0,则判断众数是否和当前值相等,若相等则cnt++,若不想等则cnt--
class Solution:
def MoreThanHalfNum_Solution(self , numbers: List[int]) -> int:
# write code here
max_group = -1
cnt = 0
for v in numbers:
if max_group == -1 or cnt == 0:
max_group = v
cnt += 1
elif max_group != v:
cnt += -1
else:
cnt += 1
return max_group