前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode23. 合并K个升序链表

LeetCode23. 合并K个升序链表

作者头像
周杰伦本人
发布2022-10-25 17:26:45
2440
发布2022-10-25 17:26:45
举报
文章被收录于专栏:同步文章

思路:优先队列

代码语言:javascript
复制
//给你一个链表数组,每个链表都已经按升序排列。
//
// 请你将所有链表合并到一个升序链表中,返回合并后的链表。
//
//
//
// 示例 1:
//
// 输入:lists = [[1,4,5],[1,3,4],[2,6]]
//输出:[1,1,2,3,4,4,5,6]
//解释:链表数组如下:
//[
//  1->4->5,
//  1->3->4,
//  2->6
//]
//将它们合并到一个有序链表中得到。
//1->1->2->3->4->4->5->6
//
//
// 示例 2:
//
// 输入:lists = []
//输出:[]
//
//
// 示例 3:
//
// 输入:lists = [[]]
//输出:[]
//
//
//
//
// 提示:
//
//
// k == lists.length
// 0 <= k <= 10^4
// 0 <= lists[i].length <= 500
// -10^4 <= lists[i][j] <= 10^4
// lists[i] 按 升序 排列
// lists[i].length 的总和不超过 10^4
//
// Related Topics 链表 分治 堆(优先队列) 归并排序
// 👍 1416 👎 0


//leetcode submit region begin(Prohibit modification and deletion)

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * 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> queue = new PriorityQueue<ListNode>(lists.length, new Comparator<ListNode>() {
            @Override
            public int compare(ListNode listNode, ListNode t1) {
                if (listNode.val<t1.val) {
                    return -1;
                } else if (listNode.val== t1.val) {
                    return 0;
                } else {
                    return 1;
                }
            }
        });

        ListNode listNode = new ListNode(0);
        ListNode p = listNode;
        for (ListNode node : lists) {
            if (node!=null) {
                queue.add(node);
            }
        }
        while (!queue.isEmpty()) {
            p.next = queue.poll();
            p= p.next;
            if (p.next!=null) {
                queue.add(p.next);
            }
        }
        return listNode.next;
    }
}
//leetcode submit region end(Prohibit modification and deletion)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-07-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档