题目标题

合并K个有序链表

参考解析
  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6. class Solution:
  7. def mergeKLists(self, lists: List[ListNode]) -> ListNode:
  8. import heapq
  9. dummy = ListNode(0)
  10. p = dummy
  11. head = []
  12. for i in range(len(lists)):
  13. if lists[i] :
  14. heapq.heappush(head, (lists[i].val, i))
  15. lists[i] = lists[i].next
  16. while head:
  17. val, idx = heapq.heappop(head)
  18. p.next = ListNode(val)
  19. p = p.next
  20. if lists[idx]:
  21. heapq.heappush(head, (lists[idx].val, idx))
  22. lists[idx] = lists[idx].next
  23. return dummy.next