-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge k Sorted Lists
118 lines (78 loc) · 2.4 KB
/
Merge k Sorted Lists
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
// Merge k Sorted Lists
// 3 solutions
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# 1.
class Solution:
def merge(self, l1, l2):
head = temp = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
temp.next = l1
l1 = l1.next
else:
temp.next = l2
l2 = l2.next
temp = temp.next
if l1:
temp.next = l1
# l1 = l1.next
if l2:
temp.next = l2
return head.next
def mergeKLists(self, A: List[Optional[ListNode]]) -> Optional[ListNode]:
if A == []:
return None
ok = A[0]
for a in A[1:]:
ok = self.merge(ok, a)
return ok
# 2.
class Solution:
def merge(self, l1, l2):
if l1 == None:
return l2
if l2 == None:
return l1
head = temp = ListNode(0)
if l2.val < l1.val:
l1, l2 = l2, l1
head.next = l1
while l1 and l2:
while l1 and l1.val <= l2.val:
temp = l1
l1 = l1.next
temp.next = l2
l1, l2 = l2, l1
return head.next
def mergeKLists(self, A: List[Optional[ListNode]]) -> Optional[ListNode]:
if A == []:
return None
ok = A[0]
for a in A[1:]:
ok = self.merge(ok, a)
return ok
# 3. Using min Heap
class Solution:
def mergeKLists(self, A: List[Optional[ListNode]]) -> Optional[ListNode]:
minHeap = []
count = 0
for l in A:
if l != None:
count += 1
ok = (l.val, count, l)
heappush(minHeap, ok)
head = temp = ListNode(0)
while len(minHeap) > 0:
val, c, l = heappop(minHeap)
temp.next = l
l = l.next
temp = temp.next
if l != None:
count += 1
ok = (l.val, count, l)
heappush(minHeap, ok)
return head.next