Problem
https://leetcode.com/problems/merge-k-sorted-lists
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.
Hint
Try using min heap structure.
Solution
Code
Simple
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<int, vector<int>, greater<int>> minHeap;
for (auto list : lists)
for (ListNode* it=list; it != nullptr; it = it->next)
minHeap.push(it->val);
ListNode* head = nullptr;
for (ListNode* current = nullptr; !minHeap.empty();) {
ListNode* node = new ListNode(minHeap.top());
if (head == nullptr)
head = node;
else
current->next = node;
current = node;
minHeap.pop();
}
return head;
}
};
Whole Code with Test Case
// https://leetcode.com/problems/merge-k-sorted-lists
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<int, vector<int>, greater<int>> minHeap;
for (auto list : lists)
for (ListNode* it=list; it != nullptr; it = it->next)
minHeap.push(it->val);
ListNode* head = nullptr;
for (ListNode* current = nullptr; !minHeap.empty();) {
ListNode* node = new ListNode(minHeap.top());
if (head == nullptr)
head = node;
else
current->next = node;
current = node;
minHeap.pop();
}
return head;
}
};
int main() {
Solution s = Solution();
}
Complexity
Time
Time complexity will be O(n*log n).
First loop has a time complexity of O(n* log n), and the second loop also has a time complexity of O(n*log n).
Space
Space complexity will be O(n).
Best Solution (Pinned)
Overall
'알고리즘 문제 > Leetcode' 카테고리의 다른 글
[C++] Leetcode 57. Insert Interval (Hint, Solution) (0) | 2023.04.27 |
---|---|
[C++] Leetcode 3. Longest Substring Without Repeating Characters (Hint, Solution, Time and Space Complexity) (0) | 2023.04.21 |
[C++] Leetcode 73. Set Matrix Zeroes (Hint, Solution) (0) | 2023.04.07 |
[C++] Leetcode 322. Coin Change (Hint, Solution) (0) | 2023.03.30 |
[C++] Leetcode 70. Climbing Stairs (Hint, Solution) (0) | 2023.03.29 |