Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
/**
* 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 == null || lists.length == 0){
return null;
}
Queue<ListNode> heap = new PriorityQueue<ListNode>(lists.length, ListNodeComparator);
for(int i=0; i<lists.length; i++){
if(lists[i] != null){
heap.add(lists[i]);
}
}
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
while(!heap.isEmpty()){
ListNode head = heap.poll();
tail.next = head;
tail = head;
if(head.next != null){
heap.add(head.next);
}
}
return dummy.next;
}
private Comparator<ListNode> ListNodeComparator = new Comparator<ListNode>(){
public int compare(ListNode n1, ListNode n2){
if(n1 == null){
return 1;
}
if(n2 == null){
return -1;
}
return n1.val - n2.val;
}
};
}