数组中出现次数超过一半的数字
2019-12-22 本文已影响0人
而立之年的技术控
微信图片_20191222215040.jpg
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
if not numbers:
return 0
count = 0
value = None
for i in numbers:
if value == None and count == 0:
value = i
count += 1
if value != None and count > 0:
if value == i:
count += 1
else:
count -= 1
if count == 0:
value = None
count2 = 0
if value:
for i in numbers:
if i == value:
count2 += 1
if 2*count2 > len(numbers):
return value
else:
return 0