Merge k sorted linked lists and return it as one sorted list.
Analyze and describe its complexity.
Example
Given lists:
[
2->4->null,
null,
-1->null
],
return -1->2->4->null
.
K路归并算法,使用heap的方式处理
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param lists: a list of ListNode
* @return: The head of one sorted list.
*/
public ListNode mergeKLists(List<ListNode> lists) {
// write your code here
if (lists == null || lists.size() == 0) {
return null;
}
ListNode dummy = new ListNode(0);
ListNode head = dummy;
Comparator<ListNode> cmp = new Comparator<ListNode>() {
public int compare(ListNode a, ListNode b) {
return a.val - b.val;
}
};
PriorityQueue<ListNode> heap = new PriorityQueue<>(10, cmp);
for (int i = 0; i < lists.size(); i++) {
ListNode node = lists.get(i);
while (node != null) {
heap.offer(node);
node = node.next;
}
}
while (!heap.isEmpty()) {
head.next = heap.poll();
head = head.next;
}
return dummy.next;
}
}