-
Notifications
You must be signed in to change notification settings - Fork 4
/
merge_k_sorted_lists.py
46 lines (38 loc) · 1.09 KB
/
merge_k_sorted_lists.py
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""Created by sgoswami on 8/22/17."""
import heapq
"""Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity."""
from python.ds.heap import MinHeap
class LinkedList:
def __init__(self):
self.head = None
def add(self, item):
curr = self.head
while curr.next:
curr = curr.next
curr.next = ListNode(item)
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
heap, count = MinHeap(), 0
if not lists or len(lists) == 0:
return None
for item in lists:
while item:
count += 1
heap.push(item.val)
item = item.next
head = curr = ListNode(0)
while count > 0:
item = heap.pop()
p = ListNode(item)
curr.next = p
curr = curr.next
count -= 1
return head.next