3.31 练手

Leetcode 23题

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6

解决方法:

使用最小堆解决

import heapq
class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        h = [] #minheap
        for listTemp in lists:
            while listTemp!=None:
                h.append(listTemp.val)                    #O(n)
                listTemp = listTemp.next
        heapq.heapify(h) # make h as a min heaq           O(n)
                         #this is an in-place function
       
        if len(h)==0:
            return []
        rootNote = ListNode(heapq.heappop(h))
        currentNote = rootNote
        while len(h)!=0: #h not empty
            currentNote.next = ListNode(heapq.heappop(h))
            currentNote = currentNote.next
            
        return rootNote

算上出堆调整时间复杂度为O(nlogn),想吐槽的地方是 while not h 一定要写成 while len(h)!=0 ,但是看stackoverflow上有人说可以这么写的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值