leetcode第23题:合并K个排序链表

首先我想到的是采用一般递归法,将K个链表合并化为(k-1)两个链表合并

class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        # 运用递归, 化K个链表相加为两个链表相加
        if not lists : return 
        n = len(lists)
        for i in range(1,n):
            lists[0] = self.mergeList(lists[0],lists[i])
        return lists[0]
    
    def mergeList(self,l1,l2):
        head = ListNode(-1)
        p = head
        if not l1:return l2
        if not l2:return l1
        while l1 and l2:
            if l1.val<l2.val:
                head.next = l1
                l1 = l1.next
            else:
                head.next = l2
                l2 = l2.next
            head = head.next
        if not l1:head.next =l2
        if not l2:head.next =l1
        return p.next

但是时间复杂度超过了O(N^2)

显然一个一个加太费时间了,这里可以用分而治之算法。它将问题的实例划分为若干个较小的实例(最好拥有相同的规模)。

分而治之算法是递归的,使用分而治之(D&C)解决问题的过程包括两个步骤:

  1. 找出递归边界条件,这种条件必须尽可能简单
  2. 不断地将问题分解(或者说缩小规模),直到符合递归边界条件。

本题递归边界:两个链表相加

将列表中的链表循环两两相加,最终得到结果。

class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        # 运用分而治之
        if not lists : return 
        n = len(lists)
        nums = 1
        while nums<n:
            for i in range(0,n-nums,nums *2):
                lists[i] = self.mergeList(lists[i],lists[i+nums])
            nums = nums *2
        return lists[0]
    
    def mergeList(self,l1,l2):
        head = ListNode(-1)
        p = head
        if not l1:return l2
        if not l2:return l1
        while l1 and l2:
            if l1.val<l2.val:
                head.next = l1
                l1 = l1.next
            else:
                head.next = l2
                l2 = l2.next
            head = head.next
        if not l1:head.next =l2
        if not l2:head.next =l1
        return p.next

 

posted @ 2019-08-27 16:54  耳东三羊  阅读(175)  评论(0)    收藏  举报