Description
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 1:
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
Example 2:
Input: lists = []
Output: []
Example 3:
Input: lists =
Output: []
Constraints:
k == lists.length
0 <= k <= 104
0 <= lists[i].length <= 500
-104 <= lists[i][j] <= 104
lists[i]
is sorted in ascending order.
- The sum of
lists[i].length
will not exceed 104
.
Code
以下所有做法都符合 T(n)=2T(2n)+O(n),因此
Time Complexity: O(nlogn), Space Complexity: O(1)
Divide and Conquer
以 Merge Two Sorted Lists 為基礎,Divide and Conquer。
Iteratively merge head and tail
當合併完頭尾後,偶數長度會少一半,奇數長度則為 (listsSize + 1) / 2
,奇數更新的方式也可以用在偶數長度上。
Iteratively merge through interval
Source