zoukankan      html  css  js  c++  java
  • 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       # 返回链表
    

      

  • 相关阅读:
    面试基础02
    CustomerView
    Java封装性
    Java中参数传递机制:值传递
    Java重载 (Overlaod)与几个面试题
    数据结构、算法概述和简单的JVM内存解析
    异常捕捉

    面向接口的编程方式
    看程序的方法
  • 原文地址:https://www.cnblogs.com/bad-robot/p/10065019.html
Copyright © 2011-2022 走看看