leetcode题解记录-23 合并k个升序链表(python3)

题目

23 合并k个升序链表
题目链接
官方题解

代码记录

from typing import List
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def resort(self,lists):
        lists = [n for n in lists if n]
        if len(lists)<=1:
            return lists
        cur = lists[0].val
        left = 1
        right = len(lists)-1
        while left<=right:
            mid = (left+right)//2
            if lists[mid].val <= cur:
                left = mid+1
            else:
                right = mid-1
        target = (left+right)//2
        return lists[1:target+1]+[lists[0]]+lists[target+1:]

    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        lists = [n for n in lists if n]
        if not lists:
            return None
        lists.sort(key= lambda x:x.val)
        head = ListNode(0)
        cur = head
        while lists:
            cur.next = ListNode(lists[0].val)
            cur = cur.next
            lists[0]=lists[0].next
            lists=self.resort(lists)
        return head.next
#测试用例
L1=ListNode(1)
L1.next=ListNode(4)
L1.next.next=ListNode(5)
L2=ListNode(1)
L2.next=ListNode(3)
L2.next.next=ListNode(4)
L3=ListNode(2)
L3.next=ListNode(6)

S=Solution()
res=S.mergeKLists([L1,L2,L3])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值