本来想把第一个依次和其他所有的链表进行合并的 可惜超时了
class Solution {
private:
ListNode* mergeTwoList(ListNode *l1,ListNode *l2)
{
ListNode *prenode=new ListNode(0);
ListNode *tail=prenode;
while(l1&&l2)
{
if(l1->val<l2->val)
{
tail->next=l1;
tail=tail->next;
l1=l1->next;
}
else
{
tail->next=l2;
tail=tail->next;
l2=l2->next;
}
}
if(l1)
tail->next=l1;
if(l2)
tail->next=l2;
return prenode->next;
}
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
int n=lists.size();
if(n==0)
return NULL;
for(int i=1;i<n;i++)
{
lists[0]=mergeTwoList(lists[0],lists[i]);
}
return lists[0];
}
};
下面的代码是不断地将相连的两个进行归并 直到只剩下一个链表 而且使用的是迭代的方式进行归并 击败了82%的代码, 后面我想试试用递归的方式进行归并 看下效率
class Solution {
private:
ListNode* mergeTwoList(ListNode *l1,ListNode *l2)
{
ListNode *prenode=new ListNode(0);
ListNode *tail=prenode;
while(l1&&l2)
{
if(l1->val<l2->val)
{
tail->next=l1;
tail=tail->next;
l1=l1->next;
}
else
{
tail->next=l2;
tail=tail->next;
l2=l2->next;
}
}
if(l1)
tail->next=l1;
if(l2)
tail->next=l2;
return prenode->next;
}
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
int n=lists.size();
if(n==0)
return NULL;
else if(n==1)
return lists[0];
int currentList=n;//记录总共的链表的数量
while(currentList!=1) {
int j = 0;
for (int i = 0; i < currentList; i += 2) {
if (i == currentList - 1) {
lists[j++] = lists[i];
}
else {
lists[j++] = mergeTwoList(lists[i], lists[i + 1]);
}
}
currentList = j;
}
return lists[0];
}
};
下面是用递归的方式实现归并 感觉没有效率上的降低 都是击败了82%
class Solution {
private:
ListNode* mergeTwoList(ListNode *l1,ListNode *l2)
{
ListNode *prenode=new ListNode(0);
ListNode *tail=prenode;
while(l1&&l2)
{
if(l1->val<l2->val)
{
tail->next=l1;
tail=tail->next;
l1=l1->next;
}
else
{
tail->next=l2;
tail=tail->next;
l2=l2->next;
}
}
if(l1)
tail->next=l1;
if(l2)
tail->next=l2;
return prenode->next;
}
ListNode *merge(vector<ListNode*>& lists,int l,int r)
{
if(r-l==1)
{
return mergeTwoList(lists[l],lists[r]);
}
else if(r==l)
return lists[r];
else
{
ListNode * llist;
ListNode * rlist;
int mid=(l+r)/2;
llist=merge(lists,l,mid);
rlist=merge(lists,mid+1,r);
return mergeTwoList(llist,rlist);
}
}
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
int n=lists.size();
if(n==0)
return NULL;
else if(n==1)
return lists[0];
return merge(lists,0,n-1);
}
};