leetcode第23题python合并K个有序链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    """
    23. 合并K个升序链表
    给你一个链表数组,每个链表都已经按升序排列。请你将所有链表合并到一个升序链表中,返回合并后的链表。
    """
    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
        # 思路:直接上最容易理解的分治法,将问题转化为合并两个升序链表的遍历问题
        # 1. 初始化和特殊处理
        # if not lists or not lists[0]:  # 易错点not lists[0],这种情况只能考虑只有一个链表元素的情况
        if not lists:
            return None
        count = len(lists)
        if count == 1:
            return lists[0]
        
        # 2、遍历
        while len(lists) > 1:
            first = lists.pop()
            second = lists.pop()
            three = self.mergeTwoLists(first, second)
            lists.append(three)
        
        # 3、返回结果
        return lists[0]

    # 定义合并两个有序链表的方法
    def mergeTwoLists(self, first: Optional[ListNode], second: Optional[ListNode]) -> Optional[ListNode]:
        if not first:
            return second
        elif not second:
            return first
        elif first.val < second.val:
            first.next = self.mergeTwoLists(first.next, second)
            return first
        else: 
            second.next = self.mergeTwoLists(first, second.next)
            return second

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ICPunk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值