-
Notifications
You must be signed in to change notification settings - Fork 29
/
0023-Merge-k-Sorted-Lists.py
77 lines (67 loc) · 1.85 KB
/
0023-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
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
'''
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# Method 1
class Solution:
def mergeTwoLists(self, l1, l2):
res = cur = ListNode()
while l1 and l2:
if l1.val <= l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 or l2
return res.next
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
if not lists:
return None
last = len(lists) - 1
while last:
i, j = 0, last
while i < j:
lists[i] = self.mergeTwoLists(lists[i], lists[j])
i += 1
j -= 1
last -= 1
return lists[0]
# Method 2
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
if not lists:
return None
last = len(lists) - 1
while last:
i, j = 0, last
while i < j:
res = cur = ListNode()
first, second = lists[i], lists[j]
while first and second:
if first.val <= second.val:
cur.next = first
first = first.next
else:
cur.next = second
second = second.next
cur = cur.next
cur.next = first or second
lists[i] = res.next
i += 1
j -= 1
last -= 1
return lists[0]