Merge k Sorted Lists
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.
Code1
private ListNode mergeHelper_v1_minHeap(List<ListNode> lists) {
// initial priorityQueue
Queue<ListNode> pq = new PriorityQueue<ListNode>(lists.size(), new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
return o1.val - o2.val;
}
});
for (ListNode head : lists) {
if (head != null) {
pq.offer(head);
}
}
ListNode dummy = new ListNode(0), tail = dummy;
while (!pq.isEmpty()) {
ListNode top = pq.poll();
tail.next = top;
tail = top;
if (top.next != null) {
pq.offer(top.next);
}
}
return dummy.next;
}Code2
Code3
Last updated