【发布时间】:2022-01-26 04:47:00
【问题描述】:
406. Queue Reconstruction by Height
以上问题的最佳答案是这样的。
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
heap = []
for person in people:
heapq.heappush(heap, (-person[0], person[1]))
result = []
while heap:
person = heapq.heappop(heap)
result.insert(person[1], [-person[0], person[1]])
return result
上述方法是优先队列方法。
另一方面,使用排序的方法是这样的。
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(key = lambda x:(x[0],-x[1]))
result = []
while people:
person = people.pop()
result.insert(person[1], [person[0],person[1]])
return result
big-O 类似。 但我不知道为什么我们应该使用更复杂的优先级队列。优先队列相对于排序有什么优势?
【问题讨论】:
-
这里没有真正的理由使用优先队列。 (如果这些解决方案中的 任何一个 是渐近最优的,我会感到惊讶。这些都是最坏情况 O(n^2),而且似乎 O(n log n) 解决方案应该是可能的。 )
-
“但我不知道为什么我们应该使用更复杂的优先级队列。” 这个问题有一个谬误;您假设管理优先级队列比运行排序算法更“复杂”。首先,不清楚在这种情况下“复杂”是什么意思。第二,你听说过堆排序吗?这是一种相对简单的排序算法,它依赖于优先级队列。相比之下,我会说 Timsort(这是在 python 中使用
list.sort时调用的算法)比 heapsort 更“复杂”。 -
在评论(回答)中,您提到您有一个
insert操作。这将使一切变得不同。如果是这种情况,我建议您在问题中添加该信息(带有代码),因为这对于回答问题至关重要。 -
@Stef 我认为
list.sort是一个直观而简洁的代码。我不明白堆排序更简单。
标签: python algorithm sorting priority-queue heap