K路归并排序,将K路都放入最小堆构建起来,每次都取最小放入新的队列,然后将对应的队列再取一个放入堆中。
/**
* 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> heap = new PriorityQueue<ListNode>(10,new Comparator<ListNode>(){
@Override
public int compare(ListNode n1, ListNode n2)
{
return n1.val-n2.val;
}
});
for(int i=0;i<lists.length;i++)
{
ListNode node = lists[i];
if(node!=null)
{
heap.offer(node);
}
}
ListNode head = null;
ListNode pre = head;
while(heap.size()>0)
{
ListNode cur = heap.poll();
if(head == null)
{
head = cur;
pre = head;
}
else
{
pre.next = cur;
}
pre = cur;
if(cur.next!=null)
heap.offer(cur.next);
}
return head;
}
}