s0023
This commit is contained in:
parent
d55c9c43ea
commit
8d4732c963
21
include/s0023_merge_k_sorted_lists.hpp
Normal file
21
include/s0023_merge_k_sorted_lists.hpp
Normal 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
|
43
src/s0023_merge_k_sorted_lists.cpp
Normal file
43
src/s0023_merge_k_sorted_lists.cpp
Normal 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);
|
||||
}
|
Loading…
Reference in New Issue
Block a user