Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
可以直接两两合并,比较慢.
考虑分治算法.f(i,j)表示合并序号为i~j的链表.
如果i==j,显然不用合并.
如果i j相邻,合并v[i], v[j]
否则,二分,合并i~mid,mid+1~j的两部分链表,再把这两部分合并.
虽然LeetCode上标记为hard,个人感觉不是很难,没有本地测试,两遍AC,42ms
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<ListNode*> v; //我自己的数组,方便在函数外操作
ListNode* merge(ListNode* l1, ListNode* l2) //合并两个链表
{
if(l1 == NULL)
return l2;
if(l2 == NULL)
return l1;
ListNode* head = NULL;
if(l1->val <= l2->val)
{
head = l1; l1 = l1->next;
}
else
{
head = l2; l2 = l2->next;
}
ListNode* it = head;
while(l1!=NULL && l2!=NULL)
{
if(l1->val <= l2->val)
{
it->next = l1;
l1 = l1->next;
}
else
{
it->next = l2;
l2 = l2->next;
}
it = it->next;
}
if(l1)
it->next = l1;
if(l2)
it->next = l2;
return head;
}
ListNode* f(int i,int j) //合并i~j之间的链表,返回值就是合并后的值
{
if(i == j)
return v[i];
if(j == i+1)
{
return merge(v[i],v[j]); //将v[i]和v[j]合并
}
int mid = (i+j)/2;
return merge(f(i,mid),f(mid+1,j));
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
int len = lists.size();
if(len == 0)
return NULL;
for(int i=0;i<len;i++)
{
v.push_back(lists[i]);
}
return f(0,len-1);
}
};