合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
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(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
int k=lists.length;
if(k==0)
return null;
PriorityQueue<ListNode> minHeap = new PriorityQueue<ListNode>(k,new Comparator<ListNode>(){
@Override
public int compare(ListNode i1,ListNode i2){
return i1.val-i2.val;
}
});
for(int i=0;i<k;i++){
if(lists[i]!=null)
minHeap.add(lists[i]);
}
ListNode head=new ListNode(-1);
ListNode cur=head;
while(!minHeap.isEmpty()){
ListNode tmp=minHeap.poll();
if(tmp.next!=null){
minHeap.add(tmp.next);
}
cur.next=tmp;
cur=cur.next;
}
return head.next;
}
}