Merge K Sorted Linked Lists Into One
Implement mergeKLists
Given an array of
k linked lists, each already sorted in non-decreasing order, merge all of them into one sorted linked list and return its head.
This is a direct extension of merging two sorted lists (see "Merge Two Sorted Linked Lists Into One") — the question is how to combine k of them without doing needlessly repeated work. A divide and conquerDivide and Conquer MergeSplit the k lists in half, recursively reduce each half down to a single sorted list, then merge those two results with an ordinary two-list merge. Halving at every level means each node only participates in about log k merges total, instead of up to k merges if lists were combined one at a time into a growing result. approach splits the array of lists in half, recursively merges each half down to one list, and combines the two halves with the same two-pointer splice used for two lists — turning k lists into one in O(N log k) instead of the O(N·k) that merging them one at a time would cost.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Example 2:
Input: lists = [[]]
Output: []
Example 3:
Input: lists = [[],[1],[2,3]]
Output: [1,2,3]
+ 5 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ k (number of lists) ≤ 10 - ●
0 ≤ number of nodes in each list ≤ 20 - ●
-10⁴ ≤ node value ≤ 10⁴ - ●
Each individual list is already sorted in non-decreasing order
lists =
[[1,4,5], [1,3,4], [2,6]]