Algorithm 算法:多数元素
我正在为多数元素问题编写一个分而治之的解决方案,在这个解决方案中,如果n个整数序列中有一个元素出现的次数超过n/2次,则必须输出1,否则必须输出0。我的代码对于我能想到的任何测试用例都能完美地工作,但是评分系统一直说它为测试用例提供了错误的答案Algorithm 算法:多数元素,algorithm,python-3.x,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(a
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)
n=int(输入())
数组=输入().split()
对于范围(n)中的i:
数组[i]=int(数组[i])
def合并(列表、blist):
a=len(alist)
b=len(blist)
n=a+b
结果=[]
对于范围(n)中的i:
如果len(alist)>0且len(blist)>0:
如果列表[0]1:
n=len(数字)
列表=数字[:(n//2)]
blist=数字[(n//2):]
alist=合并排序(alist)
blist=合并排序(blist)
数字=合并(列表、blist)
返回号码
数组=合并排序(数组)
键=数组[n//2]
计数=0
对于范围(n)中的i:
如果数组[i]==键:
计数+=1
如果计数>(n//2):
印刷品(1)
其他:
打印(0)
有人能告诉我代码中的错误吗?展开回答:
在合并
功能中,当处理一个列表
用尽的情况时,另一个列表
与扩展
一起添加到组合的列表
的末尾,但是循环没有终止,非空的列表
没有清除,因此如果终端扩展
提前发生,非空列表的其余部分将重复多次。将循环更改为以下内容,使用扩展
s剩余列表
(添加额外清理以减少代码长度)的端子箱:
你能提供有问题的测试用例吗?为什么重新实现排序?任何广义排序的Python实现都会比内置的运行慢得多?这是任务的限制吗?还有什么其他限制?@Nurzhan:这就是问题所在。他们只是说我的代码在一个测试用例中失败了,但没有提供那个测试用例。@ShadowRanger:这是一个算法分配。我试图通过构建自己的排序函数来更好地理解分而治之的技术。因此,我想明确一点,您是否需要编写自己的排序函数?还是你只需要构建问题的主要部分?似乎如果您正试图找到问题,那么您可能希望首先使用内置的sorted
实现多数元素部分,然后在完成多数元素算法后重新实现一个drop-in替换sorted
。
# 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
# Reverse once up front, so you can pop from right, not left
alist.reverse()
blist.reverse()
# Stop when first list exhausted, not after fixed repetitions
while alist and blist:
if alist[-1] < blist[-1]:
result.append(alist.pop())
else:
result.append(blist.pop())
# Only one will have contents, simpler to just unconditionally extend,
# rather than test and extend, since extending with empty list is harmless
result += alist[::-1]
result += blist[::-1]