Python-8: 找出整型数组中占比超过一半的数
问题描述
小R从班级中抽取了一些同学,每位同学都会给出一个数字。已知在这些数字中,某个数字的出现次数超过了数字总数的一半。现在需要你帮助小R找到这个数字。
代码:
def solution(array):
if not array:
return 0
candidate = array[0]
count = 1
for num in array[1:]:
if num == candidate:
count += 1
else:
count -= 1
if count == 0:
candidate = num
count = 1
# 验证候选元素是否确实出现次数超过一半
count = 0
for num in array:
if num == candidate:
count += 1
if count > len(array) // 2:
return candidate
else:
return 0
if __name__ == "__main__":
# Add your test cases here
print(solution([1, 3, 8, 2, 3, 1, 3, 3, 3]) == 3)