1
+ # 第一种思路,寻找当前最小的节点,然后将一个放入新的节点内
2
+ # 不需要额外的存储空间,时间复杂度O(N)N为所有节点的个数和
3
+ # 4048ms 10.24%
4
+
5
+ # Definition for singly-linked list.
6
+ # class ListNode:
7
+ # def __init__(self, x):
8
+ # self.val = x
9
+ # self.next = None
10
+
11
+ class Solution :
12
+ def mergeKLists (self , lists ):
13
+ """
14
+ :type lists: List[ListNode]
15
+ :rtype: ListNode
16
+ """
17
+ # 首先剔除空链表
18
+ lists = [item for item in lists if isinstance (item , ListNode )]
19
+ if not lists :
20
+ return []
21
+
22
+ temp_list = [listnode .val for listnode in lists ]
23
+ index = temp_list .index (min (temp_list ))
24
+
25
+ mid = head = lists [index ]
26
+ lists [index ] = lists [index ].next
27
+ if lists [index ] is None :
28
+ lists .pop (index )
29
+
30
+ while lists :
31
+ temp_list = [listnode .val for listnode in lists ]
32
+
33
+ index = temp_list .index (min (temp_list ))
34
+
35
+ mid .next = lists [index ]
36
+ mid = mid .next
37
+
38
+ lists [index ] = lists [index ].next
39
+ if lists [index ] is None :
40
+ lists .pop (index )
41
+
42
+ return head
43
+
44
+ # 第二种思路,根据答案的Approach 5: Merge with Divide And Conquer
45
+ # 这里需要使用自己之前写的融合两个链表的代码
46
+ # 96ms 66.31%
47
+
48
+ class Solution :
49
+ def mergeKLists (self , lists ):
50
+ """
51
+ :type lists: List[ListNode]
52
+ :rtype: ListNode
53
+ """
54
+ if not lists :
55
+ return lists
56
+ interval = 1
57
+ while interval < len (lists ):
58
+ index = 0
59
+ while index < len (lists ) - interval :
60
+ lists [index ] = self .mergeTwoLists (lists [index ], lists [index + interval ])
61
+ index += 2 * interval
62
+ interval *= 2
63
+ return lists [0 ]
64
+
65
+ def mergeTwoLists (self , l1 , l2 ):
66
+ if not l1 :
67
+ return l2
68
+ if not l2 :
69
+ return l1
70
+ main , sub = (l2 , l1 ) if l1 .val > l2 .val else (l1 , l2 )
71
+
72
+ main_mid = main
73
+ sub_mid = sub
74
+
75
+ while main_mid .next is not None :
76
+ if main_mid .next .val >= sub_mid .val :
77
+
78
+ temp_node = sub_mid
79
+ sub_mid = sub_mid .next
80
+
81
+ next_node = main_mid .next
82
+ main_mid .next = temp_node
83
+ temp_node .next = next_node
84
+
85
+ main_mid = temp_node
86
+
87
+ if sub_mid is None :
88
+ return main
89
+ else :
90
+ main_mid = main_mid .next
91
+ main_mid .next = sub_mid
92
+ return main
0 commit comments