题目:
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:[1->4->5,1->3->4, 2->6]
输出: 1->1->2->3->4->4->5->6
代码:
一、优化的两个有序链表排序
/*
思想;倒着想,每次保证l1指向是最小的,返回给上一层,要考虑特殊情况
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1 == nullptr) return l2;
if(l2 == nullptr) return l1;
if(l1->val > l2->val) //交换两个指针
{
ListNode* temp = l1;
l1 = l2;
l2 = temp;
}
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}
};
`二、未优化的k个有序链表排序``
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size() == 0)
return NULL;
if(lists.size() == 1)
return lists[0];
ListNode* ret = lists[0];
for(int i = 1; i < lists.size(); i++)
{
//两个有序链表合并
if(ret == NULL)
{
ret = lists[i];
continue;
}
if(lists[i] == NULL)
continue;
if(ret->val > lists[i]->val)
{
ListNode* temp = ret;
ret = lists[i];
lists[i] = temp;
}
//上面保证了两个非空且ret初值比lists[i]小
ret = mergeTwo(NULL, ret,lists[i],ret);
}
return ret;
}
private:
ListNode* mergeTwo(ListNode* l1_before, ListNode* l1, ListNode* l2, ListNode* ret)
{
if(l1 == NULL)
{
l1_before->next = l2;
return ret;
}
if(l2 == NULL)
return ret;
if(l1->val > l2->val)
{
ListNode* temp = l2->next;
l1_before->next = l2;
l1_before = l2;
l2->next = l1;
l2 = temp;
}
else
{
l1_before = l1;
l1 = l1->next;
}
mergeTwo(l1_before, l1, l2, ret);
return ret;
}
};