mergeKLists

23. 合并K个排序链表
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。

示例:

输入:
[
  1->4->5,
  1->3->4,
  2->6
]
输出: 1->1->2->3->4->4->5->6
通过次数134,183提交次数257,914
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(new Comparator<ListNode>() {
            @Override
            public int compare(ListNode o1, ListNode o2) {
                return o1.val - o2.val;
            }
        });
        for(ListNode listNode: lists){
            if(listNode != null){
                queue.add(listNode);
            }
        }
        ListNode res = new ListNode(-1);
        ListNode head = res;
        while(!queue.isEmpty()){
            ListNode node = queue.poll();
            head.next = node;
            head = head.next;
            if(node.next!=null){
                queue.add(node.next);
            }
        }
        return res.next;
    }
}
原文地址:https://www.cnblogs.com/athony/p/13191624.html