两种方法
参考了评论区及官方的做法,简单记录
分治法
优先队列
1. 分治法
/**
* 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* mergeTwoLists(ListNode* a, ListNode* b) {
if ((!a) || (!b)) return a?a:b;
ListNode* dummyNode = new ListNode(0);
ListNode* p = dummyNode;
ListNode* pa = a, *pb = b;
while(pa && pb) {
if (pa->val < pb->val) {
p->next = pa;
pa = pa->next;
}else {
p->next = pb;
pb = pb->next;
}
p = p->next;
}
p->next = pa?pa:pb;
return dummyNode->next;
}
ListNode* merge(vector<ListNode*>& lists, int l, int r) {
if (l>r) return nullptr;
if (l==r) return lists[l];
int mid = (l+r)>>1;
return mergeTwoLists(merge(lists, l, mid), merge(lists, mid+1, r));
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
return merge(lists, 0, lists.size()-1);
}
};
2. 优先队列
/**
* 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:
struct myComp {
constexpr bool operator()(const ListNode* a, const ListNode* b) {
return a->val > b->val;
}
};
private:
priority_queue<ListNode*, vector<ListNode*>, myComp> priQue;
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
int n = lists.size();
for(int i=0;i<n;++i) {
ListNode* tmp = lists[i];
while(tmp) {
priQue.emplace(tmp);
tmp=tmp->next;
}
}
ListNode* dummyNode = new ListNode(0);
ListNode* p = dummyNode;
while(!priQue.empty()) {
p->next = priQue.top();
priQue.top()->next = nullptr; // 不加此操作会报错,因为有可能会造成环形链表
priQue.pop();
p = p->next;
}
return dummyNode->next;
}
};