Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Solution:
/**
* 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) {
ListNode dummy = new ListNode(0);
ListNode scan = dummy;
if(lists.length==0) return dummy.next;
PriorityQueue<ListNode> pq = new PriorityQueue<>(lists.length, (a,b)->(a.val-b.val));
for(ListNode ln : lists) if(ln!=null) pq.offer(ln);
while(!pq.isEmpty()){
scan.next = pq.poll();
scan = scan.next;
if(scan.next!=null) pq.offer(scan.next);
}
return dummy.next;
}
}