题目:数组中出现次数超过一半的数字
题目描述:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
思路:遍历数组,使用字典存储每个字符出现的次数。然后求出字典中次数最大的字符,将该次数与数组长度的一半进行比较即可。
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
l = len(numbers)
counts = l // 2 + 1
d = {}
for i in numbers:
if i in d:
d[i] += 1
else:
d[i] = 1
res = sorted(d.items(), key=lambda x: x[1])
if res[-1][1] >= counts:
return res[-1][0]
else:
return 0