23. Merge k Sorted Lists
Description
Difficulty: Hard
Related Topics: Linked List, Divide and Conquer, Heap (Priority Queue), Merge Sort
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:
1 2 3 4 5 6 7 8 9 10
| 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:
1 2
| Input: lists = [] Output: []
|
Example 3:
1 2
| 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.
Hints/Notes
Solution
Language: C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
#include <queue>
class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { ListNode *dummy = new ListNode(); if (lists.size() == 0) { return dummy->next; } auto cmp = [](const ListNode* l1, const ListNode* l2) { return l1->val > l2->val; }; priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> pq(cmp); for(auto head: lists) { if (head) { pq.push(head); } } ListNode *p = dummy; while (pq.size() != 0) { ListNode *tmp = pq.top(); p->next = tmp; p = p->next; pq.pop(); if (tmp->next) { pq.push(tmp->next); } } return dummy->next; } };
|