合并K个排序链表
中英题面
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
算法
分治并结合归并排序思想。
时间复杂度:
O(NlogK)
空间复杂度:
O(logK)
代码
1 # Definition for singly-linked list. 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 class Solution: 8 def mergeKLists(self, lists): 9 """ 10 :type lists: List[ListNode] 11 :rtype: ListNode 12 """ 13 if (not lists): 14 return None 15 if (len(lists) == 1): 16 return lists[0] 17 mid = len(lists) // 2 18 hen = self.mergeKLists(lists[: mid]) 19 tai = self.mergeKLists(lists[mid :]) 20 if (not hen): 21 return tai 22 if (not tai): 23 return hen 24 if (hen.val > tai.val): 25 hen, tai = tai, hen 26 i = hen 27 while (tai): 28 if (i.next): 29 if (i.next.val > tai.val): 30 tai.next, i.next, tai = i.next, tai, tai.next 31 i = i.next 32 else: 33 i.next = tai 34 break 35 return hen