算法:多数元素

时间:2016-10-20 02:28:52

标签: algorithm python-3.x

我正在为多数元素问题编写一个分而治之的解决方案,如果n个整数序列中的元素出现超过n / 2次,则必须输出1,否则为0。我的代码适用于我能想到的任何测试用例,但是评分系统一直说它为测试用例提供了错误的答案。

n = int(input())
array = input().split()
for i in range(n):
    array[i] = int(array[i])
def merge(alist, blist):
    a = len(alist)
    b = len(blist)
    n = a + b
    result = []
    for i in range(n):
        if len(alist) > 0 and len(blist) > 0:
            if alist[0] < blist[0]:
                result.append(alist[0])
                alist.pop(0)
            else:
                result.append(blist[0])
                blist.pop(0)
        elif len(alist) == 0:
            result.extend(blist)
        elif len(blist) == 0:
            result.extend(alist)
    return result
def mergesort(numbers):
    if len(numbers) > 1:
        n = len(numbers)
        alist = numbers[:(n//2)]
        blist = numbers[(n//2):]
        alist = mergesort(alist)
        blist = mergesort(blist)
        numbers = merge(alist, blist)
    return numbers
array = mergesort(array)
key = array[n//2]
count = 0
for i in range(n):
    if array[i] == key:
        count += 1
if count > (n//2):
    print(1)
else:
    print(0)

有人能在我的代码中向我显示错误吗?

1 个答案:

答案 0 :(得分:1)

扩展comment以回答:

merge函数中,当处理一个list用尽的情况时,另一个list会添加到合并list的末尾{{1}但是,循环没有终止,并且非空extend未被清除,因此如果终端list提前发生,则重复非空extend的剩余部分多次。将循环更改为以下内容,使用list剩余extend的终端大小写(添加额外的清理以减少代码长度):

list

旁注:# Stop when first list exhausted, not after fixed repetitions while alist and blist: if alist[0] < blist[0]: result.append(alist.pop(0)) else: result.append(blist.pop(0)) # Only one will have contents, simpler to just unconditionally extend, # rather than test and extend, since extending with empty list is harmless result += alist result += blist pop(0)位于O(n)list位于.pop()。对于大型,以下将更有效:

O(1)