[Diary] Task11- title leetcode brush K merge sort list

Title Description

K merge sort list, return the list sorted combined. Please describe and analyze the complexity of algorithms

Input:
[
1-> 4-> 5,
1-> 3-> 4,
2-> 6
]
Output: 1-> 1-> 2-> 3-> 4-> 4-> 5-> 6

Problem-solving ideas

  • Violence: turn merge two ordered lists, so merger k sort the list is converted into a recursive problem
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        def mergeTwoLists(l1,l2):
            pre = ListNode(None)
            head = pre
            while l1 and l2:
                if l1.val <= l2.val:
                    pre.next = l1
                    l1 = l1.next
                    pre = pre.next
                else:
                    pre.next = l2
                    l2 = l2.next
                    pre = pre.next
            pre.next = l1 if l1 else l2
            return head.next
        if not lists:
            return
        r = lists[0]
        for i in range(1,len(lists)):
            r = mergeTwoLists(r,lists[i])
        return r

Here Insert Picture Description

  • Conquer method: carried out on the basis of Violence Act on the improvement is finally merge together twenty-two merger, reducing the time complexity
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        def mergeTwoLists(l1,l2):
            pre = ListNode(None)
            head = pre
            while l1 and l2:
                if l1.val <= l2.val:
                    pre.next = l1
                    l1 = l1.next
                    pre = pre.next
                else:
                    pre.next = l2
                    l2 = l2.next
                    pre = pre.next
            pre.next = l1 if l1 else l2
            return head.next
        if not lists:
            return
        s = 1 #代表当前合并的两个链表的索引差
        n = len(lists)
        while s < n:
            for i in range(0,n,2 * s):
                if i + s <= n - 1:
                    lists[i] = mergeTwoLists(lists[i],lists[i + s])
            s *= 2
        return lists[0]

Here Insert Picture Description

to sum up

  • For questions always feel the brush solution can only come up with violence, may not be the real algorithms applied to solving problems, hope to continue refueling, the algorithm is applied to solving problems in the real
Published 45 original articles · won praise 2 · Views 1247

Guess you like

Origin blog.csdn.net/soulmate______/article/details/104815672