跳至主要內容

23. 合并K个升序链表

专题leetcodeleetcode小于 1 分钟

23. 合并K个升序链表

题目:

给你一个链表数组,每个链表都已经按升序排列。

请你将所有链表合并到一个升序链表中,返回合并后的链表。

leetcode地址:https://leetcode.cn/problems/merge-k-sorted-lists/open in new window

solution

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) return null;
        ListNode virtualNode = new ListNode(-1);
        ListNode index = virtualNode;
        PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(lists.length, (o1, o2) -> (o1.val - o2.val));
        for(ListNode node : lists) {
            if (node != null) {
                queue.add(node);
            }
        }

        while(!queue.isEmpty()){
            ListNode minNode = queue.poll();
            index.next = minNode;
            index = index.next;
            if (minNode.next != null) {
                queue.add(minNode.next);
            }
        }
        return virtualNode.next;
    }
}

版权申明

本站点所有内容,版权均归https://wenchao.renopen in new window所有,除非明确授权,否则禁止一切形式的转载协议

打赏

微信 支付宝

上次编辑于:
打赏
给作者赏一杯咖啡吧
您的支持将是我继续更新下去的动力
微信微信
支付宝支付宝