题目:
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
算法一:
暴力法;
时间复杂度:
O
(
N
l
o
g
N
)
O(NlogN)
O(NlogN)
空间复杂度:
O
(
N
)
O(N)
O(N)
代码:
/**
* 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) {
vector<int> arry;
for(auto i=lists.begin();i!=lists.end();i++)
{
ListNode *p=*i;
while(p)
{
arry.push_back(p->val);
p=p->next;
}
}
ListNode *temp=new ListNode(0);
ListNode *head=temp;
sort(arry.begin(),arry.end());
for(auto j=arry.begin();j!=arry.end();j++)
{
head->next=new ListNode(*j);
head=head->next;
}
return temp->next;
}
};
执行结果:
算法二:
两两合并;
时间复杂度:
O
(
K
N
)
O(KN)
O(KN)
空间复杂度:
O
(
1
)
O(1)
O(1)
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
ListNode *temp=new ListNode(1);
ListNode *ret=temp;
while(l1!=NULL&&l2!=NULL)
{
if(l1->val<l2->val)
{
temp->next=l1;
l1=l1->next;
}
else
{
temp->next=l2;
l2=l2->next;
}
temp=temp->next;
}
temp->next=l1==NULL?l2:l1;
return ret->next;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size()==0) return NULL;
ListNode *result=lists[0];
for(int i=1;i<lists.size();i++)
{
result=mergeTwoLists(result,lists[i]);
}
return result;
}
};
执行结果:
算法三:
分治法;
时间复杂度:
O
(
N
l
o
g
k
)
O(Nlogk)
O(Nlogk)
空间复杂度:
O
(
1
)
O(1)
O(1)
代码:
/**
* 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)
{
int n=lists.size();
if(n==0) return NULL;
return merge(lists,0,n-1);
}
ListNode*merge(vector<ListNode *>&lists,int begin,int end)
{
if(begin==end) return lists[begin];
else
{
int mid=begin+end>>1;
ListNode* l1=merge(lists,begin,mid);
ListNode* l2=merge(lists,mid+1,end);
ListNode* temp=new ListNode(-1);
ListNode* head=temp;
while(l1&&l2)
{
if(l1->val<l2->val)
{
head->next=l1;
l1=l1->next;
}
else
{
head->next=l2;
l2=l2->next;
}
head=head->next;
}
head->next=l1?l1:l2;
return temp->next;
}
}
};
执行结果: