Merge
k
sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
Solution
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
k = len(lists)
if k == 0:
return None
interval = 1
while interval < k:
for i in range(0, k - interval, interval * 2):
lists[i] = self.merge2Lists(lists[i], lists[i + interval])
interval *= 2
return lists[0]
def merge2Lists(self, l1, l2):
head = point = ListNode(0)
while l1 and l2:
if l1.val <= l2.val:
point.next = l1
l1 = l1.next
else:
point.next = l2
l2 = l2.next
point = point.next
if not l1:
point.next = l2
else:
point.next = l1
return head.next
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
k = len(lists)
resolved = 0
head = ListNode()
cur = head
minHeap = []
for i in range(k):
if not lists[i]:
resolved += 1
else:
heapq.heappush(minHeap, (lists[i].val, i))
while minHeap:
val, idx = heapq.heappop(minHeap)
n = lists[idx]
node = ListNode(n.val)
cur.next = node
cur = cur.next
lists[idx] = lists[idx].next
if lists[idx]:
heapq.heappush(minHeap, (lists[idx].val, idx))
return head.next