Brush title - K merge sort list

Look at the title

K merge sort list, return the list sorted combined. Please complexity analysis and description of the algorithm.

Example:

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


Accordance with the rules to get the title, first of all to violence again, to get all the data into the array sort it, then put in a linked list

ps: too long without contact list, and finished ... almost forgot to write next time still use -> next = - =

# 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:
        self.nodes = []
        head = point = ListNode(0)
        for l in lists:
            while l:
                self.nodes.append(l.val)
                l = l.next
        for x in sorted(self.nodes):
            point.next = ListNode(x)
            point = point.next
        return head.next

Time spent 224ms

Then we see what save time algorithm

First, let's try to analyze only two of the list when

I went LeetCode above search, we really have this problem

https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/he-bing-liang-ge-you-xu-lian-biao-by-leetcode/

The two ordered lists into a new sorted list and return. The new list is by all nodes in a given mosaic composed of two lists.

Example:

Input: 1-> 2-> 4, 1-> 3-> 4
Output: 1-> 1-> 2-> 3-> 4-> 4


Since it is already sorted, it is the first to compare these two lists of numbers, a relatively small next, then compare again, small election next loop forever

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        head = ListNode(0)
        point = head
        while l1 and l2:
            if l1.val <= l2.val:
                point.next = l1
                l1 = l1.next
            else:
                point.next = l2
                l2 = l2.next
            point = point.next
        if l1:
            point.next = l1
        else:
            point.next = l2
        return head.next

K then placed inside a linked list, you can also take this approach, there is more use of such terms queue

Reference: Baidu priority queue.

from Queue import PriorityQueue
class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        q = PriorityQueue()
        head = point = ListNode(0)
        for l in lists:
            if l:
                q.put((l.val,l))
        while not q.empty():
            val, node = q.get()
            point.next = ListNode(val)
            point = point.next
            node = node.next
            if node:
                q.put((node.val, node))
        return head.next

The time it takes 192ms, than the slightly faster time violence

I can not think of any way, only to refer to the solution of the problem, connect below.
Links: https://leetcode-cn.com/problems/two-sum/solution/he-bing-kge-pai-xu-lian-biao-by-leetcode/

This algorithm pairwise merge algorithms are optimized.

Have to say, I did that to merge two lists of two topics have not thought this question through to do a round of methods, but directly to merge two lists methods (without hearing the smallest on inside the final list) directly with a = - =

Can only say it is too brain-dead friends, learned today, also posted the code below:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
from Queue import PriorityQueue
class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        len_of_lists = len(lists)
        if len_of_lists == 0:
            return 
        len_of_next = 1
        while len_of_next < len_of_lists:
            for i in range(0, len_of_lists - len_of_next, len_of_next*2):
                lists[i] = self.merge2Lists(lists[i], lists[i+len_of_next])
            len_of_next *= 2
        return lists[0]
    def merge2Lists(self, l1, l2):
        head = point = ListNode(0)
        while l1 and l2:
            if l1.val <= l2.val:
                point.next = ListNode(l1.val)
                l1 = l1.next
            else:
                point.next = ListNode(l2.val)
                l2 = l2.next
            point = point.next
        if l1:
            point.next = l1
        else:
            point.next = l2
        return head.next

This question is used three methods, also optimized, feel learned a lot, think the problem later when the pattern to be slightly larger

Guess you like

Origin www.cnblogs.com/fanwenkeer/p/11270796.html