-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergeKSortedLists.py
84 lines (77 loc) · 2.06 KB
/
MergeKSortedLists.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
# Definition for singly-linked list.
# 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
"""
n = ListNode(0)
answer = n
v = []
for item in lists:
while item:
v.append(item.val)
item = item.next
v.sort()
for val in v:
n.next = ListNode(val)
n = n.next
return answer.next
#divide and conquer
# Definition for singly-linked list.
# 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
"""
if not lists:
return
if len(lists) == 1:
return lists[0]
mid = len(lists) // 2
l = self.mergeKLists(lists[0:mid])
r = self.mergeKLists(lists[mid:])
return self.merge(l, r)
def merge(self, l, r):
res = ListNode(0)
answer = res
while l and r:
if l.val < r.val:
res.next = ListNode(l.val)
l = l.next
else:
res.next = ListNode(r.val)
r = r.next
res = res.next
res.next = l or r
return answer.next
#priority queue
from Queue import PriorityQueue
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
head = point = ListNode(0)
q = PriorityQueue()
for l in lists:
if l:
q.put((l.val, l))
while not q.empty():
val, node = q.get()
point.next = ListNode(val)
point = point.next
node = node.next
if node:
q.put((node.val, node))
return head.next