[LintCode 104] 合并k个排序链表(Python)

本文介绍了一种有效的算法来合并多个已排序的链表。通过两两合并的方法,最终得到一个完全排序的链表。文章还分析了该算法的时间复杂度为O(nklogk),空间复杂度为O(1)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

合并k个排序链表,并且返回合并后的排序链表。尝试分析和描述其复杂度。
样例
给出3个排序链表[2->4->null,null,-1->null],返回 -1->2->4->null

思路

两两合并,如果是奇数,余出来的直接加在最后。

代码

"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""


class Solution:
    """
    @param lists: a list of ListNode
    @return: The head of one sorted list.
    """
    def mergeKLists(self, lists):
        # write your code here
        if lists is None or len(lists) == 0:
            return None
        while len(lists) > 1:
            tmp = []
            for i in range(0, len(lists) - 1, 2):
                p = self.mergeTwoList(lists[i], lists[i + 1])
                tmp.append(p)
            if len(lists) % 2 == 1:
                tmp.append(lists[-1])
            lists = tmp
        return lists[0]

    def mergeTwoList(self, l1, l2):
        if l1 is None:
            return l2
        if l2 is None:
            return l1
        res = ListNode(0)
        r = res
        while l1 is not None and l2 is not None:
            if l1.val <= l2.val:
                r.next = l1
                l1 = l1.next
            else:
                r.next = l2
                l2 = l2.next
            r = r.next
        if l1 is not None:
            r.next = l1
        if l2 is not None:
            r.next = l2
        return res.next

复杂度分析

时间复杂度 O(nklogk) ,空间复杂度 O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值