合并K个排序链表
中英题面
合并k个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
Mergeksorted 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 <br /><br /><br /><br />
算法
分治并结合归并排序思想。
时间复杂度:
O(NlogK)
空间复杂度:
O(logK)
代码
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ if (not lists): return None if (len(lists) == 1): return lists[0] mid = len(lists) // 2 hen = self.mergeKLists(lists[: mid]) tai = self.mergeKLists(lists[mid :]) if (not hen): return tai if (not tai): return hen if (hen.val > tai.val): hen, tai = tai, hen i = hen while (tai): if (i.next): if (i.next.val > tai.val): tai.next, i.next, tai = i.next, tai, tai.next i = i.next else: i.next = tai break return hen
相关推荐
earthhouge 2020-08-15
dbhllnr 2020-06-04
koushr 2020-11-12
范范 2020-10-28
zhaochen00 2020-10-13
Mars的自语 2020-09-27
steeven 2020-09-18
kka 2020-09-14
qiangde 2020-09-13
聚沙成塔积水成渊 2020-08-16
aanndd 2020-08-12
范范 2020-07-30
bluetears 2020-07-28
mingyunxiaohai 2020-07-19
horizonheart 2020-07-19
liushall 2020-07-18
bluetears 2020-07-05
fengshantao 2020-07-02
liuweixiao0 2020-06-27