給你一個連結清單數組,每個連結清單都已經按升序排列。
請你将所有連結清單合并到一個升序連結清單中,傳回合并後的連結清單。
示例 1:輸入:lists = [[1,4,5],[1,3,4],[2,6]]
輸出:[1,1,2,3,4,4,5,6]
解釋:連結清單數組如下:
[
1->4->5,
1->3->4,
2->6
]
将它們合并到一個有序連結清單中得到。
1->1->2->3->4->4->5->6
示例 2: 輸入:lists = []
輸出:[]
示例 3: 輸入:lists = [[]]
輸出:[]
提示: -
k == lists.length
-
0 <= k <= 10^4
-
0 <= lists[i].length <= 500
-
-10^4 <= lists[i][j] <= 10^4
-
按 升序 排列lists[i]
-
的總和不超過lists[i].length
10^4
#
# @lc app=leetcode.cn id=23 lang=python3
#
# [23] 合并K個升序連結清單
#
# @lc code=start
# 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[ListNode]) -> ListNode:
import queue
q = queue.PriorityQueue()
head = ListNode()
p = head
cnt = 0
for node in lists:
if node:
cnt+=1
q.put((node.val,cnt,node))
while(not q.empty()):
val, tmp, node = q.get()
p.next = ListNode(val)
p=p.next
node=node.next
if node:
cnt+=1
q.put((node.val, cnt, node))
return head.next
# @lc code=end