题目:https://leetcode-cn.com/problems/merge-k-sorted-lists/
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
我的方法一:分治
将多个链表递归拆成两部分进行合并,当分拆成2或者1个时,使用https://leetcode-cn.com/problems/merge-two-sorted-lists/submissions/ 合并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:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size() == 0){
return nullptr;
}else if(lists.size() == 1){
return lists[0];
}
int n = lists.size();
vector<ListNode*> l1;
vector<ListNode*> l2;
for(int i = 0; i<n / 2; i++){
l1.push_back(lists[i]);
}
for(int i = n / 2; i<n; i++){
l2.push_back(lists[i]);
}
ListNode* l1_ordered = mergeKLists(l1);
ListNode* l2_ordered = mergeKLists(l2);
return mergeTwoLists(l1_ordered, l2_ordered);
}
private:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode dummy;
ListNode* tail = &dummy;
ListNode* cur1 = l1;
ListNode* cur2 = l2;
while(cur1 && cur2) {
if(cur1->val <= cur2->val) {
tail->next = cur1;
cur1 = cur1->next;
}else{
tail->next = cur2;
cur2 = cur2->next;
}
tail = tail->next;
tail->next = nullptr;
}
if(cur1) {
tail->next = cur1;
}
if(cur2) {
tail->next = cur2;
}
return dummy.next;
}
};
网友评论