forked from y-ncao/Python-Study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge_k_Sorted_Lists.py
More file actions
29 lines (26 loc) · 821 Bytes
/
Merge_k_Sorted_Lists.py
File metadata and controls
29 lines (26 loc) · 821 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
"""
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param a list of ListNode
# @return a ListNode
def mergeKLists(self, lists):
pq = []
for node in lists:
if node is not None:
heapq.heappush(pq, (node.val, node))
dummy = ListNode(0)
cur = dummy
while len(pq) > 0:
val, node = heapq.heappop(pq)
cur.next = node
cur = cur.next
if node.next is not None:
heapq.heappush(pq, (node.next.val, node.next))
return dummy.next
# Remember this to use Priority Queue