|
1 | | -import heapq |
| 1 | +# Approach: Heap |
| 2 | + |
| 3 | +# n = total number of nodes, k = no. of linked lists |
| 4 | +# Time: O(n * log k) |
| 5 | +# Space: O(k) |
2 | 6 |
|
3 | 7 | # Definition for singly-linked list. |
4 | 8 | # class ListNode: |
5 | 9 | # def __init__(self, val=0, next=None): |
6 | 10 | # self.val = val |
7 | 11 | # self.next = next |
8 | 12 |
|
| 13 | +import heapq |
| 14 | + |
9 | 15 | class Solution: |
10 | 16 | def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: |
11 | | - q = [(l.val, idx) for idx, l in enumerate(lists) if l] |
12 | | - heapq.heapify(q) |
13 | | - |
14 | | - head = curr = ListNode(None) |
15 | | - |
16 | | - while q: |
17 | | - val, idx = heapq.heappop(q) |
18 | | - curr.next = ListNode(val) |
19 | | - curr = curr.next |
20 | | - node = lists[idx] = lists[idx].next |
21 | | - if node: |
22 | | - heapq.heappush(q, (node.val, idx)) |
23 | | - |
24 | | - return head.next |
| 17 | + heap = [] |
| 18 | + |
| 19 | + # Add the first node from each list to the heap |
| 20 | + # We store (value, list_index, node) in heap |
| 21 | + for i, lst in enumerate(lists): |
| 22 | + if lst: |
| 23 | + heapq.heappush(heap, (lst.val, i, lst)) |
| 24 | + |
| 25 | + dummy = ListNode(0) |
| 26 | + current = dummy |
| 27 | + |
| 28 | + while heap: |
| 29 | + val, i, node = heapq.heappop(heap) |
| 30 | + |
| 31 | + # Add the node to our result list |
| 32 | + current.next = node |
| 33 | + current = current.next |
| 34 | + |
| 35 | + # If there are more nodes in the same list, add the next node to heap |
| 36 | + if node.next: |
| 37 | + heapq.heappush(heap, (node.next.val, i, node.next)) |
| 38 | + |
| 39 | + return dummy.next |
| 40 | + |
0 commit comments