Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 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) {
if(lists.length==0) return null;
PriorityQueue<ListNode> pq = new PriorityQueue<>( (node1,node2)->node1.val-node2.val );//java8 comparator
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
for(ListNode node:lists){
if(node!=null){
pq.offer(node);
}
}
while(!pq.isEmpty()){
tail.next = pq.poll();
tail = tail.next;
if(tail.next!=null){
pq.offer(tail.next);
}
}
return dummy.next;
}
}