用索引数组记录每个list的位置的方法,在遇到链表数特别大的时候,会崩,因为要多次重复比较最小值
初版代码如下:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
head = cur = ListNode(val=0,next=None)
idx = []
for lis in lists:
if lis:
idx.append(lis)
while idx:
minIdx = 0
for i in range(1,len(idx)):
if idx[i].val < idx[minIdx].val:
minIdx = i
cur.next = idx[minIdx]
cur = cur.next
idx[minIdx] = idx[minIdx].next
if not idx[minIdx]:
del idx[minIdx]
return head.next
换成最小堆,问题解决。不过堆里面不能同时压入相同的元素,因此在元组第二个里面放了i,来使得每个进去的数都不一样
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
head = cur = ListNode(val=0,next=None)
idx = []
heapq.heapify(idx)
i = 0
for lis in lists:
if lis:
i += 1
heapq.heappush(idx,(lis.val,i,lis))
while idx:
val,_,node = heapq.heappop(idx)
cur.next = node
cur = cur.next
node = node.next
if node:
i += 1
heapq.heappush(idx,(node.val,i,node))
return head.next