【算法刷题】python刷题--合并链表

23 合并 K 个升序链表

python 复制代码
from typing import List,Optional
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
        


# @lc code=start
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

import heapq


class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        if not lists:
            return None
        pq = []
        dummy = ListNode(-1)
        p = dummy
        for head in lists:
            if head:
                heapq.heappush(pq,(head.val,id(head),head))
        while pq:
            node = heapq.heappop(pq)[2]
            p.next = node
            if node.next:
                heapq.heappush(pq,(node.next.val,id(node.next),node.next))
            # p指针不断前进
            p = p.next
        return dummy.next

注意点1

对 head是否为None的判断必须有:

复制代码
    for head in lists:
            if head:
                heapq.heappush(pq,(head.val,id(head),head

否则过不了测试用了None

while pq:

p.next = node

或者 p.next = ListNode(node.val) 无区别

因为p.next 会被覆盖成小顶堆的最小值,知道没值了,指向None

相关推荐
circuitsosk12 分钟前
Python 模块与包管理:import 机制、虚拟环境与 pip 完全指南
开发语言·python·pip·依赖管理·模块与包
Wang's Blog26 分钟前
PostgreSQL笔记49:向量检索核心算法、索引调优与过滤策略深度解析
笔记·算法·postgresql
weixin_4407305031 分钟前
python+request实现接口-小结
开发语言·python
疯狂打码的少年34 分钟前
【数据结构】交换类排序:冒泡与快速排序
数据结构·笔记·算法·排序算法
zlinear数据采集卡1 小时前
数据采集卡从入门到精通(38):上位机开发实战——Python/QT/LabVIEW的技术选型与分层架构
python·单片机·嵌入式硬件·qt·fpga开发·开源·labview
Nil2081 小时前
leetcode 108有序数组转换为二叉搜索树
数据结构·算法·leetcode
高频因子挖掘机1 小时前
QuantDash 成交量单位统一实战:从“手”到“股”的跨市场量化数据清洗全流程
后端·算法·github
hn小菜鸡1 小时前
LeetCode 763、划分字母区间
数据结构·算法·leetcode
Escalating_xu1 小时前
【C++ STL简介】从六大组件到容器、迭代器与算法协作
java·c++·算法