题解 | #合并k个已排序的链表#

合并k个已排序的链表

https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6

import java.util.*;
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ArrayList<ListNode> lists) {
        if (lists == null || lists.size() < 1) {
            return null;
        }
        int n = lists.size();
        if (n == 1) {
            return lists.get(0);
        }
        PriorityQueue<ListNode> pq = new PriorityQueue<>((o1, o2) -> o1.val - o2.val);
        for (int i = 0; i < n; i++) {
            if (lists.get(i) != null) {
                pq.offer(lists.get(i)); 
            }
        }
        ListNode dummy = new ListNode(-1);
        ListNode tail = dummy;
        while (!pq.isEmpty()) {
            ListNode cur = pq.poll();
            tail.next = cur;
            tail = cur;
            if (cur.next != null) {
                pq.offer(cur.next);
            }
        }
        tail.next = null;
        return dummy.next;
    }
}

全部评论

相关推荐

做人要有梦想dji:最新工位查看图片
点赞 评论 收藏
分享
想顺利毕业的猕猴桃在看牛客:好几个月没面试了,腾讯留面评吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务