Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
idea:use priority queue,it is provided by util package
package l23;
import java.util.Comparator;
import java.util.PriorityQueue;
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>(){
@Override
public int compare(ListNode o1, ListNode o2) {
// TODO Auto-generated method stub
if(o1.val > o2.val) return 1;
else if(o1.val < o2.val) return -1;
else return 0;
}
});
ListNode root = new ListNode(0);
ListNode cur = root;
for(ListNode node : lists)
if(node != null)
q.add(node);
while(!q.isEmpty()) {
cur.next = q.poll();
cur = cur.next;
if(cur.next != null)
q.add(cur.next);
}
return root.next;
}
}