【发布时间】:2021-03-14 23:59:57
【问题描述】:
我正在尝试返回列表中最小的三个项目。下面是我写的一个 O(n) 的解决方案:
def three_smallest(L):
# base case
if (len(L) == 3):
return sorted(L)
current = L[0]
(first_smallest,second_smallest,third_smallest) = three_smallest(L[1:])
if (current < first_smallest):
return (current, first_smallest, second_smallest)
elif (current < second_smallest):
return (first_smallest, current, second_smallest)
elif (current < third_smallest):
return (first_smallest, second_smallest, current)
else:
return (first_smallest,second_smallest,third_smallest)
现在我正在尝试编写一种分而治之的方法,但我不确定应该如何划分列表。任何帮助将不胜感激。
请注意,这个解决方案(据我所知)不是分而治之。这只是一个基本的递归解决方案,因为分而治之涉及将长度为 n 的列表除以整数 b,并在这些部分上调用算法。
【问题讨论】:
标签: recursion divide-and-conquer