heap类型

博客介绍了LeetCode中多链表合并问题的解法。通过将k个链表的首个非空节点放入最小堆,堆顶为当前最小数并插入结果链表。所有节点都要入堆,结束条件是堆为空。时间复杂度为O(knlogk),空间复杂度为O(k),每次插入节点后需移动指针。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

重点思想: 第一轮从k个list中拿出第一个(若每个list非空的话;有可能为空)放入minheap中,minheap一直储存k个lists中最小的那个数,对顶代表当前最小的数,需要插入result listnode。所有list每个node都要加入minheap中,所以结束条件就是minheap为空,已经便利完所有node/

Time:一共kn个node,每次插入需要O(logk),一共 O(knlogk)

Space: O(k) minheap 大小

重点:每一次将一个list中的值插入miheap中时要将指针移到下一位,方便下一次根据list的k值来加入lists[k]的下一位。

        for i in range(k):
            if lists[i]:#current listnode is not None
                heappush(h, [lists[i].val,i])
                lists[i] = lists[i].next#prepare for next around of adding into the heap
        
            cur = cur.next
            #append the next node of list k if list k has other nodes
            if lists[cur_k]:
                heappush(h,[lists[cur_k].val, cur_k])
                lists[cur_k] = lists[cur_k].next
        return res.next


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
from heapq import *
class Solution:
    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
        h = []
        k = len(lists)
        for i in range(k):
            if lists[i]:#current listnode is not None
                heappush(h, [lists[i].val,i])
                lists[i] = lists[i].next#prepare for next around of adding into the heap
        res = ListNode(0)
        cur = res
        while h:#while heap still has remaining node left
            cur_smallest_val, cur_k = heappop(h)
            cur.next = ListNode(cur_smallest_val)
            cur = cur.next
            #append the next node of list k if list k has other nodes
            if lists[cur_k]:
                heappush(h,[lists[cur_k].val, cur_k])
                lists[cur_k] = lists[cur_k].next
        return res.next


来源:题目图片来源力扣(LeetCode)

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值