Skip to content

Commit 78bd25b

Browse files
author
weiy
committed
merge K sorted lists hard
1 parent f3adcda commit 78bd25b

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

Heap/MergeKSortedLists.py

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
"""
2+
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
3+
4+
Example:
5+
6+
Input:
7+
[
8+
1->4->5,
9+
1->3->4,
10+
2->6
11+
]
12+
Output: 1->1->2->3->4->4->5->6
13+
14+
合并 k 个有序链表。
15+
16+
用了最小堆:
17+
18+
把所有的链表节点入堆,然后出堆形成新的链表即可。
19+
20+
依然依靠了内置模块,待自己书写堆。
21+
22+
测试地址:
23+
https://leetcode.com/problems/merge-k-sorted-lists/description/
24+
25+
"""
26+
# Definition for singly-linked list.
27+
# class ListNode(object):
28+
# def __init__(self, x):
29+
# self.val = x
30+
# self.next = None
31+
import heapq
32+
33+
class Solution(object):
34+
def mergeKLists(self, lists):
35+
"""
36+
:type lists: List[ListNode]
37+
:rtype: ListNode
38+
"""
39+
a = []
40+
41+
heapq.heapify(a)
42+
43+
for i in lists:
44+
while i:
45+
heapq.heappush(a, i.val)
46+
i = i.next
47+
if not a:
48+
return None
49+
50+
root = ListNode(heapq.heappop(a))
51+
head = root
52+
53+
while a:
54+
root.next = ListNode(heapq.heappop(a))
55+
root = root.next
56+
57+
return head
58+

0 commit comments

Comments
 (0)