我正在解决 Interviewbit 代码挑战Merge K Sorted Lists:
合并 k 个排序的链表并将其作为一个排序列表返回。
例子 :
1 -> 10 -> 20 4 -> 11 -> 13 3 -> 8 -> 9
将导致
1 -> 3 -> 4 -> 8 -> 9 -> 10 -> 11 -> 13 -> 20
Python 模板代码为:
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param A : list of linked list # @return the head node in the linked list def mergeKLists(self, A): pass
这是我的python 3解决方案:
from heapq import heapify, heappop, heappush
class Solution:
# @param A : list of linked list
# @return the head node in the linked list
def mergeKLists(self, A):
minheap = [x for x in A]
# print(minheap)
# heapify(minheap)
# print(minheap)
head = tail = None
# print(minheap)
while minheap:
# print(minheap)
heapify(minheap)
print([x.val for x in minheap])
minimum = heappop(minheap)
print(minimum.val)
if head is None:
head = minimum
tail = minimum
else:
tail.next = minimum
tail = minimum
if minimum.next:
heappush(minheap, minimum.next)
return head
使用未注释的打印命令,您会注意到在 while 循环的中间运行中,heappop
返回最大的元素,就好像我们正在处理一个最大堆,但我们不是!据我所知,这就是答案出错的地方。任何人都可以提出为什么 heappop 会这样工作的原因吗?以及如何纠正?