机试刷题_数组中出现次数超过一半的数字【python】
题目:数组中出现次数超过一半的数字
描述
给一个长度为 n 的数组,数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
例如输入一个长度为9的数组[1,2,3,2,2,2,5,4,2]。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param numbers int整型一维数组
# @return int整型
#
class Solution:
def MoreThanHalfNum_Solution(self , numbers: List[int]) -> int:
#
if len(numbers)==1:
return numbers[0]
nLen = len(numbers)//2
tmp = {}
for val in numbers:
if val in tmp:
tmp[val] = tmp.get(val,0)+1
else:
tmp[val] = 1
for key,val in tmp.items():
if val>nLen:
return key