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 <= 10^4
0 <= lists[i].length <= 500
-10^4 <= lists[i][j] <= 10^4
lists[i]
is sorted in ascending order.- The sum of
lists[i].length
won't exceed10^4
.
Related Topics:
Linked List, Divide and Conquer, Heap
Similar Questions:
Companies:
Facebook, Amazon, Google, Microsoft, Bloomberg, Oracle, Adobe, IXL, LinkedIn, Wish, Apple, Uber, VMware, Yahoo, Walmart Labs, Salesforce, Samsung, Mathworks
// OJ: https://leetcode.com/problems/merge-k-sorted-lists/
// Author: github.com/lzl124631x
// Time: O(NlogK)
// Space: O(K)
struct Cmp {
bool operator()(const ListNode *a, const ListNode *b) {
return a->val > b->val;
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode dummy, *tail = &dummy;
priority_queue<ListNode*, vector<ListNode*>, Cmp> q;
for (auto list : lists) {
if (list) q.push(list); // avoid pushing NULL list.
}
while (q.size()) {
auto node = q.top();
q.pop();
if (node->next) q.push(node->next);
tail->next = node;
tail = node;
}
return dummy.next;
}
};
// OJ: https://leetcode.com/problems/merge-k-sorted-lists/
// Author: github.com/lzl124631x
// Time: O(NlogK)
// Space: O(1)
class Solution {
private:
ListNode* mergeTwoLists(ListNode* a, ListNode* b) {
ListNode head, *tail = &head;
while (a && b) {
if (a->val < b->val) { tail->next = a; a = a->next; }
else { tail->next = b; b = b->next; }
tail = tail->next;
}
tail->next = a ? a : b;
return head.next;
}
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if (lists.empty()) return NULL;
for (int N = lists.size(); N > 1; N = (N + 1) / 2) {
for (int i = 0; i < N / 2; ++i) {
lists[i] = mergeTwoLists(lists[i], lists[N - 1 - i]);
}
}
return lists[0];
}
};