合并 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; }
* }
*/
public class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists.length == 0){
return null;
}
PriorityQueue<ListNode> q = new PriorityQueue<ListNode>(lists.length,
new Comparator<ListNode>() {
public int compare(ListNode a, ListNode b) {
if (a.val > b.val){
return 1;
}
else if(a.val == b.val){
return 0;
}
else {
return -1;
}
}
});
for (ListNode list : lists) {
if (list != null){
q.add(list);
}
}
ListNode head = new ListNode(0);
ListNode p = head;
while (q.size() > 0) {
ListNode temp = q.poll();
p.next = temp;
if (temp.next != null){
q.add(temp.next);
}
p = p.next;
}
return head.next;
}
}