继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

23. 合并K个排序链表

富国沪深
关注TA
已关注
手记 294
粉丝 41
获赞 158

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

示例:

输入:[  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


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP