Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
用一个priority queue,先把每个list的第一个node放进去。每次拿一个node出来,并把node.next放进去。事实上排序是由heap来做的,感觉像是作弊的样子。时间复杂度O(nklogk)。n是元素总数。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeKLists(List<ListNode> lists) {
Comparator<ListNode> comparator = new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
return o1.val - o2.val;
}
};
PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(50, comparator);
for(ListNode node : lists){
if(node != null)
queue.offer(node);
}
ListNode head = null;
ListNode pre = null;
while(!queue.isEmpty()){
ListNode node = queue.poll();
if(head == null){
head = node;
pre = node;
}
else{
pre.next = node;
}
pre = node;
if(node.next != null){
queue.offer(node.next);
}
}
return head;
}
}