23. Merge k Sorted Lists
Question:
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example:
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
Input: lists = []
Output: []
Input: lists = [[]]
Output: []
Source code
Version 1/u>
Idea:
The strategy combines with Merge Two Sorted Lists algorithm.
First, get the size of vector n
because the pair of Listnodes is necessary before calling mergeTwoLists.
At 19 line, the range of for-loop is in half, we get the left Listnode lists[i]
and the right Listnode lists[n - 1 - i]
to do merger.
After calling mergeTwoLists
, n
reduces by half until n <= 1
.
Why n is equal to (n + 1) / 2
? Because the length is odd, one remaining ListNode can not to do merger, so it must to be counted.
Time complexity: O(log(n)*(l1 + l2))
Space complexity: O(1)
1 | /** |
Verion 2
Idea:
On the another hand, it can be solved by the Priority Queue.
First, the default heap of priority queue is max-heap. However, we want to get the result in ascending order, so we should implement min-heap.
1 | /** |