This commit is contained in:
Sainnhe Park 2022-11-14 11:40:07 +08:00
parent d55c9c43ea
commit 8d4732c963
2 changed files with 64 additions and 0 deletions

View File

@ -0,0 +1,21 @@
#ifndef S0023_MERGE_K_SORTED_LISTS
#define S0023_MERGE_K_SORTED_LISTS
#include <vector>
using namespace std;
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);
};
#endif

View File

@ -0,0 +1,43 @@
#include "s0023_merge_k_sorted_lists.hpp"
ListNode *mergeTwoLists(ListNode *a, ListNode *b) {
if (a == nullptr) {
return b;
} else if (b == nullptr) {
return a;
}
ListNode dummy;
ListNode *tail = &dummy;
while (a != nullptr && b != nullptr) {
if (a->val > b->val) {
tail->next = b;
b = b->next;
} else {
tail->next = a;
a = a->next;
}
tail = tail->next;
}
if (a == nullptr) {
tail->next = b;
} else {
tail->next = a;
}
return dummy.next;
}
// 分治合并
ListNode *merge(vector<ListNode*> &lists, int l, int r) {
if (l == r) {
return lists[l];
}
if (l > r) {
return nullptr;
}
int mid = (l + r) >> 1;
return mergeTwoLists(merge(lists, 1, mid), merge(lists, mid + 1, r));
}
ListNode* Solution::mergeKLists(vector<ListNode*>& lists) {
return merge(lists, 0, lists.size() - 1);
}