输入:lists = [[1,4,5],[1,3,4],[2,6]]
输出:[1,1,2,3,4,4,5,6]
/**
* 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; }
* }
*/
/**
优先队列(顶堆)O(NlogK) O(K) :n是结点数,从优先队列中存取元素是log
3个取最小,补上,再取,顶堆为空结束
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
int len = lists.length;
if(len == 0) return null;
//优先队列
PriorityQueue<ListNode> PriorityQueue = new PriorityQueue<>(len, (x1,x2)->x1.val-x2.val);
//将node放入
for(ListNode node : lists)
if(node != null)
PriorityQueue.add(node);
//建一个头node来存储,同一个为辅助结点帮助插入
ListNode resNode = new ListNode(-1);
ListNode curNode = resNode;
//队列为空,退出
while(!PriorityQueue.isEmpty())
{
//弹出
ListNode tempNode = PriorityQueue.poll();
//辅助结点帮助插入
curNode.next = tempNode;
curNode = tempNode;
//判断弹出结点后还有结点吗
if(tempNode.next != null)
PriorityQueue.add(tempNode.next);
}
//返回结点的next
return resNode.next;
}
}