![ceb3833be37a7eb33484af58c02778c3.png](https://i-blog.csdnimg.cn/blog_migrate/0e18249173a85e0ee523c8f9b9d43471.jpeg)
题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
解析
1.构建hash表
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
hashmap = {}
if not numbers:
return 0
for i in numbers:
if i in hashmap.keys():
hashmap[i] += 1
else:
hashmap[i] = 1
for key in hashmap.keys():
if hashmap[key] > len(numbers) // 2:
return key
return 0
2.利用count计数
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
for i in numbers:
if numbers.count(i) > len(numbers) // 2:
return i
return 0