题目描述:
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
解题方案:
采用collections模块中计数器Counter就能很简单实现计数:
import collections
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
tmp = collections.Counter(numbers)
x = len(numbers)/2
for k, v in tmp.items():
if v > x:
return k
return 0
正常方法是采用了两次遍历,第一次选出出现次数最大的数,第二次计数:
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
count = 0
_max = numbers[0]
for num in numbers:
if num == _max:
count += 1
else:
count -= 1
if count < 0:
_max = num
count = 0
for num in numbers:
if num == _max:
count += 1
if count > len(numbers) // 2:
return _max
return 0