You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
from queue import PriorityQueue
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
q = PriorityQueue()
for headOfK in lists:
cur = headOfK
while cur:
q.put(cur.val)
cur = cur.next
dummy = ListNode()
cur = dummy
while q.qsize():
node = q.get()
cur.next = ListNode(node)
cur = cur.next
return dummy.next
Time Complexity: O(N*Log(N))
Space Complexity: O(N)
Time Complexity: O(N*Log(N))
Space Complexity: O(N)