leetcode 23 questions: K merge sort list

The first thing I think of is the use of general recursive method, the list will be merged into the K (k-1) merge two lists

class Solution:
     DEF mergeKLists (Self, Lists: List [ListNode]) -> ListNode:
         # use of recursion, is a sum of the K list two lists by adding 
        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

However, over the time complexity O (N ^ 2)

Obviously a a plus too much time, here-and-conquer algorithm can use points. Examples of questions will be divided into several smaller instances (best to have the same scale).

Divide and conquer algorithm is recursive use of divide and rule (D & C) problem-solving process consists of two steps:

  1. Recursively find the boundary conditions, such conditions must be as simple as possible
  2. Continue to break down the problem (or downsizing), until compliance with recursive boundary conditions.

This question recursive border: adding two lists

The chain list every two cycles are added to give the final result.

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

 

Guess you like

Origin www.cnblogs.com/cchenyang/p/11419352.html