为了账号安全,请及时绑定邮箱和手机立即绑定

23. 合并K个排序链表

标签:
机器学习

合并个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。

示例:

输入:[  1->4->5,  1->3->4,  2->6]输出:1->1->2->3->4->4->5->6

# class ListNode:

#     def __init__(self, x):

#         self.val = x

#         self.next = None

import numpy as np

class Solution:

    isFirst = True

    def mergeKLists(self, lists):

        """

        :type lists: List[ListNode]

        :rtype: ListNode

        """

        lenght = lists.__len__()

        arr = []

        while lenght >0:

            if lists[lenght-1]==None:

                lists.pop(lenght-1)

            else:

                arr.append(0)

            lenght-=1

        lenght = lists.__len__()

        if lenght==0:

            return

        list_head = ListNode(-1)

        list_node = ListNode(0)

        list_head.next = list_node

        self.isFirst =True

        # arr = np.zeros(lenght,dtype=int)

        list_node = self.digui(lists,list_node,arr )

        return list_node

    def digui(self, lists, list_node, arr):

        lenght = lists.__len__()

        if lenght == 1:

            list_node.next = lists[0]

            return list_node.next

        while lenght >0 and self.isFirst:

            arr[lenght-1] = lists[lenght-1].val

            lenght-=1

        self.isFirst = False

        # index = arr.argmin()

        index = arr.index(min(arr))

        node = ListNode(arr[index])

        list_node.next = node

        if lists[index].next == None:

            lists.pop(index)

            # arr = np.delete(arr,index,axis=0)

            arr.pop(index)

        else:

            lists[index] = lists[index].next

            arr[index] = lists[index].val

        self.digui(lists, list_node.next, arr)

        return list_node.next


webp

笔记:list 使用  内存比  array 使用少很多



作者:不爱去冒险的少年y
链接:https://www.jianshu.com/p/f87415dcf949


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消