合并k个升序链表有两种方法,第一种是每次从各个链表中取出最小值然后将该链表当前指针移至该链表该值的next重复直到所有链表的当前指针均指向None(即遍历结束)。这种方法的时间复杂度为O(kn)其中k为链表数,n为所有链表最长长度。第二种即采用分治思想,两两链表合并直至合并完所有链表。这种方法只需合并logk次,时间复杂度为O(nlogk)。本文主要给出方法二的代码实现。
示例:
图1 输入输出示意图
代码:
class Solution:
def mergeKLists(self, lists):
if not lists or len(lists) == 0:
return None
while len(lists) > 1:
temp = []
for i in range(0, len(lists), 2):
l1 = lists[i]
if i + 1 < len(lists):
l2 = lists[i + 1]
else:
l2 = None
temp.append(self.mergeTwoLists(l1, l2))
lists = temp
return lists[0]
def mergeTwoLists(self, l1, l2):
dummy = ListNode(0)
cur = dummy
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
if l1:
cur.next = l1
if l2:
cur.next = l2
return dummy.next
注意:
1)注意返回None的两种情况,区别if not xxx与xxx is None
if not lists or len(lists) == 0:
return None
关于if not xxx与xxx is None等详见: python中if not x: 和 if x is not None: 和 if not x is None的使用和区别_if not fxdyxx bb is none:-CSDN博客
2) 注意边界条件和下标范围
for i in range(0, len(lists), 2):
l1 = lists[i]
if i + 1 < len(lists):
l2 = lists[i + 1]
else:
l2 = None
对i+1的判断即防止下标溢出