Problem:
Merge
k
sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
采用分治来做。两两合并链表,直到只剩下1个链表。时间复杂度为O(m*n*log(n)),而顺序合并的时间复杂度为O(m*n^2)。
Solution:
/**
* 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;
int size = lists.size();
while(size>1)
{
for(int i=0;i<size/2;i++)
mergeTwo(lists.at(i),lists.at(size-i-1));
size = (size+1)/2;
}
return lists.at(0);
}
private:
void mergeTwo(ListNode *&n1,ListNode *&n2)
{
ListNode *p = (ListNode*)malloc(sizeof(ListNode)), *q = (ListNode*)malloc(sizeof(ListNode));
p->next = n1;
n1 = p;
q->next = n2;
n2 = q;
while(NULL!=p->next&&NULL!=q->next)
{
while(NULL!=p->next&&p->next->val<q->next->val)p = p->next;
ListNode *tmp = p->next;
p->next = q->next;
q->next = q->next->next;
p->next->next = tmp;
p = p->next;
}
if(NULL==p->next)
p->next = q->next;
free(n2);
n2 = n1;
n1 = n1->next;
free(n2);
}
};
* 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;
int size = lists.size();
while(size>1)
{
for(int i=0;i<size/2;i++)
mergeTwo(lists.at(i),lists.at(size-i-1));
size = (size+1)/2;
}
return lists.at(0);
}
private:
void mergeTwo(ListNode *&n1,ListNode *&n2)
{
ListNode *p = (ListNode*)malloc(sizeof(ListNode)), *q = (ListNode*)malloc(sizeof(ListNode));
p->next = n1;
n1 = p;
q->next = n2;
n2 = q;
while(NULL!=p->next&&NULL!=q->next)
{
while(NULL!=p->next&&p->next->val<q->next->val)p = p->next;
ListNode *tmp = p->next;
p->next = q->next;
q->next = q->next->next;
p->next->next = tmp;
p = p->next;
}
if(NULL==p->next)
p->next = q->next;
free(n2);
n2 = n1;
n1 = n1->next;
free(n2);
}
};