# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
if (numbers == None or len(numbers) <= 0):
return 0
result = numbers[0]
times = 1
length = len(numbers)
for i in range(1,length):
if times == 0:
result = numbers[i]
times = 1
elif numbers[i] == result:
times += 1
else:
times -= 1
if(self.CheckMoreThanHalf(numbers, result)):
result = 0
return result
#判断数组中出现result的次数是否超过数组长度的一半
def CheckMoreThanHalf(self, numbers, result):
times = 0
length = len(numbers)
for i in range(length):
if numbers[i] == result:
times += 1
if (times * 2 <= length):
return True
return False
剑指Offer:数组中出现次数超过一半的数字
最新推荐文章于 2017-08-21 22:51:09 发布