LeetCode:23. 合并K个排序链表

1、题目描述

  示例:

  输入:

  [

  1->4->5,

  1->3->4,

  2->6

  ]

  输出: 1->1->2->3->4->4->5->6

2、题解

2.1、解法一

  原理:分治算法,将链表列表拆分成单个链表,然后再合并

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

class Solution(object):
    
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        origin = ListNode(0)
        cur = origin
        while l2 is not None:
            while l1 is not None and l2.val > l1.val:
                cur.next = l1
                cur = cur.next
                l1 = l1.next
            cur.next = l2
            cur = cur.next
            l2 = l2.next
        cur.next = l1 if l2 is None else l2
        return origin.next
    
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        n = len(lists)
        if n == 0:
            return []
        if n == 1:
            return lists[0] # 返回链表

        mid = n//2
        left = lists[:mid]
        right = lists[mid:]

        l1 = self.mergeKLists(left)   # 返回链表
        l2 = self.mergeKLists(right)  # 返回链表
        ret = self.mergeTwoLists(l1, l2) # 将链表合并
        return ret       # 返回链表

  

原文地址:https://www.cnblogs.com/bad-robot/p/10065019.html