题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6?tpId=295&tqId=724&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param lists ListNode类一维数组 # @return ListNode类 # import heapq class Solution: def mergeKLists(self, lists: list[ListNode]) -> ListNode: # write code here dummy=ListNode(-1) p=dummy head=[ ] for i in range(len(lists)): #如果listsi为真,将i在List中的索引和i中链表的值添加到堆中,这一步实际上将2个链表的头结点添加入堆中了 if lists[i]: heapq.heappush(head,(lists[i].val,i) ) lists[i]=lists[i].next while head: #当Head为真的时候,取出堆顶的元素 val,idx =heapq.heappop(head) #构建新的链表节点并将p指向新节点,然后将新节点命名为p p.next=ListNode(val) p=p.next #。 if lists[idx]: heapq.heappush(head,(lists[idx].val,idx)) lists[idx]=lists[idx].next return dummy.next