Skip to content

Commit c14030a

Browse files
committed
add 23 merge sorted lists with heap
1 parent 5db7faf commit c14030a

File tree

2 files changed

+75
-1
lines changed

2 files changed

+75
-1
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
---
2+
layout: leetcode
3+
title: "23. Merge k Sorted Lists"
4+
categories: [leetcode]
5+
---
6+
7+
[Leetcode Link](https://leetcode.com/problems/merge-k-sorted-lists/)
8+
9+
10+
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
11+
12+
Merge all the linked-lists into one sorted linked-list and return it.
13+
14+
```
15+
Example 1:
16+
17+
Input: lists = [[1,4,5],[1,3,4],[2,6]]
18+
Output: [1,1,2,3,4,4,5,6]
19+
Explanation: The linked-lists are:
20+
[
21+
1->4->5,
22+
1->3->4,
23+
2->6
24+
]
25+
merging them into one sorted list:
26+
1->1->2->3->4->4->5->6
27+
Example 2:
28+
29+
Input: lists = []
30+
Output: []
31+
Example 3:
32+
33+
Input: lists = [[]]
34+
Output: []
35+
36+
37+
Constraints:
38+
39+
k == lists.length
40+
0 <= k <= 10^4
41+
0 <= lists[i].length <= 500
42+
-10^4 <= lists[i][j] <= 10^4
43+
lists[i] is sorted in ascending order.
44+
The sum of lists[i].length won't exceed 10^4.
45+
```
46+
47+
# Solution
48+
49+
The idea is useful when sorting or finding the median value of multiple disks which cannot be loaded into memory.
50+
51+
```python
52+
import heapq
53+
54+
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
55+
h = [(head.val, idx, head) for idx, head in enumerate(lists) if head]
56+
heapq.heapify(h)
57+
dummy = ListNode()
58+
last = dummy
59+
while h:
60+
val, idx, node = heapq.heappop(h)
61+
last.next = node
62+
last = last.next
63+
if node.next:
64+
heapq.heappush(h, (node.next.val, idx, node.next))
65+
return dummy.next
66+
```

media/js/tag-search-data.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,14 +87,22 @@ var problems = {
8787
templates: ["merge_sort"],
8888
notes: "Use dummy head",
8989
},
90-
"22": {
90+
"22": {
9191
name: "22. Generate Parentheses",
9292
url: "/leetcode/22-generate-parentheses",
9393
tags: ["backtrack", "array"],
9494
keywords: ["parentheses", "lv_3"],
9595
templates: ["backtrack"],
9696
notes: "Backtrack template. convert to validate the combinations of (). ",
9797
},
98+
"23": {
99+
name: "23. Merge k Sorted Lists",
100+
url: "/leetcode/23-merge-k-sorted-lists",
101+
tags: ["linked_list", "heap"],
102+
keywords: ["merge lists", "lv_1"],
103+
templates: [],
104+
notes: "Heap, add heads of lists into a heap, O(NlogK)",
105+
},
98106
"25": {
99107
name: "25. Reverse Nodes in k-Group",
100108
url: "/leetcode/25-reverse-nodes-in-k-group",

0 commit comments

Comments
 (0)