-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0023_merge-k-sorted-lists.py
66 lines (56 loc) · 1.68 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
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
head = None
current = None
while True:
indexes = self.getMinIndexes(lists)
if len(indexes) == 0:
break
for index in indexes:
val = lists[index].val
lists[index] = lists[index].next
if head is None:
head = ListNode(val)
current = head
else:
current.next = ListNode(val)
current = current.next
return head
def getMinIndexes(self, lists):
min = None
indexes = []
for index in range(0, len(lists)):
list = lists[index]
if list is None:
continue
if min is None or min == list.val:
min = list.val
indexes.append(index)
elif min > list.val:
min = list.val
indexes.clear()
indexes.append(index)
return indexes
if __name__ == '__main__':
# lists = [[1, 4, 5], [1, 3, 4], [2, 6]]
lists = [
ListNode(1, ListNode(4, ListNode(5))),
ListNode(1, ListNode(3, ListNode(4))),
ListNode(2, ListNode(6)),
]
solution = Solution()
head = solution.mergeKLists(lists)
# 查看
current = head
while current is not None:
print(current.val)
current = current.next