【发布时间】:2016-08-22 17:00:27
【问题描述】:
我在 Python 3 中的“多数元素”分而治之算法实现中无法获得正确的输出。
这应该是比较正确的;但是,我仍然会觉得我遗漏了一些东西,或者它有点不对劲,我不知道为什么会这样。
我尝试了一些调试语句和不同的东西。看起来在代码上方注释中列出的特定情况下,当它进行递归调用时,它为“left_m”解析-1,为“right_m”解析941795895。当它将每个索引处的元素与这些变量进行比较时,计数器显然永远不会增加。
我是不是走错了路?任何帮助将不胜感激。
谢谢。
# Input:
# 10
# 2 124554847 2 941795895 2 2 2 2 792755190 756617003
# Your output:
# 0
#
# Correct output:
# 1
def get_majority_element(a, left, right):
if left == right:
return -1
if left + 1 == right:
return a[left]
left_m = get_majority_element(a, left, (left + right - 1)//2)
right_m = get_majority_element(a, (left + right - 1)//2 + 1, right)
left_count = 0
for i in range(0, right):
if a[i] == left_m:
left_count += 1
if left_count > len(a)//2:
return left_m
right_count = 0
for i in range(0, right):
if a[i] == right_m:
right_count += 1
if right_count > len(a)//2:
return right_m
return -1
if __name__ == '__main__':
input = sys.stdin.read()
n, *a = list(map(int, input.split()))
if get_majority_element(a, 0, n) != -1:
print(1)
else:
print(0)
【问题讨论】:
-
为什么给定样本输入的正确输出是
1而不是2?1甚至不在输入中! -
我猜它应该是二进制的,比如如果有多数元素返回 1,否则返回 0。
标签: python algorithm python-3.x divide-and-conquer