数组中出现次数超过一半的数字
2019-03-27 本文已影响0人
momo1023
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
l = len(numbers)
if l <= 0:
return 0
cur = numbers[0]
count = 1
for i in range(1, l):
if count == 0:
cur = numbers[i]
count = 1
else:
if cur == numbers[i]:
count += 1
else:
count -= 1
# 验证
count = 0
for num in numbers:
if num == cur:
count += 1
if count > l / 2:
return cur
else:
return 0