LeetCode:23合并K个升序链表

java 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists == null || lists.length == 0){
            return null;
        }
        //设置优先队列
        PriorityQueue<ListNode> pq = new PriorityQueue<>(
            lists.length,
            (a,b) -> a.val - b.val
        );

        ListNode dummy = new ListNode(0);
        ListNode curr = dummy;
        //放入每个数组的第一个元素
        for(ListNode head : lists){
            if(head != null){
                pq.offer(head);
            }
        }
        //排序
        while(!pq.isEmpty()){
            ListNode minNode = pq.poll();
            curr.next = minNode;
            curr = curr.next;

            if(minNode.next != null){
                pq.offer(minNode.next);
            }
        }
        return dummy.next;
    }
}

单步解析:

java 复制代码
 PriorityQueue<ListNode> pq = new PriorityQueue<>(

      lists.length,

      (a,b) -> a.val - b.val

);

设置优先队列PriorityQueue,底层是二叉堆,可以保证每次取出的元素是最大或者最小的;第一个参数lists.length为设置初始容量,不写默认是11,如果装不下系统会自动扩容,但是扩容会及其消耗性能。 (a,b) -> a.val - b.val为Lambda表达式,返回值a.val - b.val为负数系统认为a比b小,为小根堆;a比b大为大根堆;相等则一样大。

java 复制代码
  for(ListNode head : lists){

    if(head != null){

        pq.offer(head);

    }

}

这部分代码在将lists元素存入pq中时只将每个数组的第一个元素存入到了pq中去,这样做既节约内存,也节省时间。

java 复制代码
if(minNode.next != null){

    pq.offer(minNode.next);

}

这里加入以第一个为例,在存入进1后,因为还有后续元素,会将4再存入到队列中去,原队列就从原来的1,1,2变成了1,2,4。

相关推荐
8Qi820 小时前
LeetCode 516:最长回文子序列
算法·leetcode·职场和发展·动态规划
马士兵教育21 小时前
Java还有前景吗?Java+AI大模型学习路线及项目?
java·人工智能·python·学习·机器学习
youngerwang1 天前
【从搬运工到协处理器:网卡芯片架构、算法、验证与边缘演进深度剖析】
网络·算法·架构·芯片
想要成为糕糕手1 天前
前端必修课:JavaScript 数组与数据结构底层逻辑全解析
javascript·数据结构·面试
snow@li1 天前
Java:理解 Gradle / 后端项目的管家 / 打包SpringBoot 应用 / 完成编译、下载依赖、运行测试、打包 JAR/WAR / 速查表
java
KaMeidebaby1 天前
卡梅德生物技术快报|纯化重组蛋白实操详解
人工智能·python·tcp/ip·算法·机器学习
云烟成雨TD1 天前
Spring AI 1.x 系列【57】动态工具发现:Tool Search Tool
java·人工智能·spring
zfoo-framework1 天前
[修改代码使用]codex官方app中使用中转(不需要cc-switch) 1.config.toml 2.sk方式登录
java
逍遥德1 天前
MQTT教程详解-05.SpringBoot集成mqtt client 性能分析
java·spring boot·spring·mt
云烟成雨TD1 天前
Spring AI 1.x 系列【54】Retry 机制分析
java·人工智能·spring