[编程题]数组中出现次数超过一半的数字
数组中出现次数超过一半的数字
http://www.nowcoder.com/questionTerminal/e8a1b01a2df14cb2b228b30ee6a92163
和leetcode有点区别,主要在于输入不保证一定有答案。
最后加上一个判断最多个数的有没有超过一半就好了。
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
if len(numbers) == 0: return 0
count = 0
for n in numbers:
if count == 0:
count = 1
ans = n
else:
if ans == n: count += 1
else: count -= 1
# 答案计数,确认正确✅
count = sum(map(lambda x:x==ans, numbers))
return ans if count > len(numbers)//2 else 0