forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
merge-k-sorted-lists.py
114 lines (96 loc) · 3.06 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
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
# Time: O(nlogk)
# Space: O(1)
# Merge k sorted linked lists and return it as one sorted list.
# Analyze and describe its complexity.
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self:
return "{} -> {}".format(self.val, self.next)
# Merge two by two solution.
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
def mergeTwoLists(l1, l2):
curr = dummy = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
curr.next = l1 or l2
return dummy.next
if not lists:
return None
left, right = 0, len(lists) - 1;
while right > 0:
if left >= right:
left = 0
else:
lists[left] = mergeTwoLists(lists[left], lists[right])
left += 1
right -= 1
return lists[0]
# Time: O(nlogk)
# Space: O(logk)
# Divide and Conquer solution.
class Solution2:
# @param a list of ListNode
# @return a ListNode
def mergeKLists(self, lists):
def mergeTwoLists(l1, l2):
curr = dummy = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
curr.next = l1 or l2
return dummy.next
def mergeKListsHelper(lists, begin, end):
if begin > end:
return None
if begin == end:
return lists[begin]
return mergeTwoLists(mergeKListsHelper(lists, begin, (begin + end) / 2), \
mergeKListsHelper(lists, (begin + end) / 2 + 1, end))
return mergeKListsHelper(lists, 0, len(lists) - 1)
# Time: O(nlogk)
# Space: O(k)
# Heap solution.
import heapq
class Solution3:
# @param a list of ListNode
# @return a ListNode
def mergeKLists(self, lists):
dummy = ListNode(0)
current = dummy
heap = []
for sorted_list in lists:
if sorted_list:
heapq.heappush(heap, (sorted_list.val, sorted_list))
while heap:
smallest = heapq.heappop(heap)[1]
current.next = smallest
current = current.next
if smallest.next:
heapq.heappush(heap, (smallest.next.val, smallest.next))
return dummy.next
if __name__ == "__main__":
list1 = ListNode(1)
list1.next = ListNode(3)
list2 = ListNode(2)
list2.next = ListNode(4)
print Solution().mergeKLists([list1, list2])