方法1:暴力,k个链表按顺序合并
时间复杂度:
(n+n)+(2n+n)+...+ ((k-1)n + n) = (1+2+...+k-1)n + (k-1)n = (1+2+...+k-1+k)n -n = (k^2+k-1)/2*n = O(k^2*n)
方法2:将k*n个结点放到vector,再将vector排序,再将结点顺序相连
设有K个链表,平均每个链表有n个结点,时间复杂度:
kN*logkN +kN = O(kN*logkN)
方法3:对k个链表进行分治,两两进行合并
设有k个链表,平均每个链表有n个结点,时间复杂度:
第一轮:进行k/2次,每次处理2n个数字
第2轮,进行k/4次,每次处理4n个数字
...
最后一次,进行k/(2^logk)次,每次处理2^logk*n个数
2n*k/2+...+2^logk*n * k/(2^logk)
= nk + nk +...+nk = O(knlogk)
//方法2:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
bool cmp(const ListNode* a,const ListNode* b)
{
return a->val < b->val;
}
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
vector<ListNode*> node;
for(int i =0;i<lists.size();++i)
{
ListNode* head = lists[i];
while(head)
{
node.push_back(head);//将每个结点加入结点数组
head = head->next;
}
}
if(node.size() == 0)
return nullptr;
sort(node.begin(),node.end(),cmp);
for(int i =0;i<node.size();++i)
node[i]->next = node[i+1];
node[node.size()-1]->next = nullptr;
return node[0];
}
};
方法3:
/**
* 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 p(0);
ListNode* pre = &p;
while(l1 && l2)
{
if(l1->val < l2->val)
{
pre->next = l1;
l1 = l1->next;
}else{
pre->next = l2;
l2 = l2->next;
}
pre = pre->next;
}
if(l1)
pre->next = l1;
if(l2)
pre->next = l2;
return p.next;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size() == 0)
return nullptr;
if(lists.size() == 1)
return lists[0];
if(lists.size() == 2)
return mergeTwoLists(lists[0],lists[1]);
int mid = lists.size()/2;
vector<ListNode*> sub1;
vector<ListNode*> sub2;
for(int i =0;i<mid;++i)
sub1.push_back(lists[i]);
for(int i =mid;i<lists.size();++i)
sub2.push_back(lists[i]);
ListNode* l1 = mergeKLists(sub1);
ListNode* l2 = mergeKLists(sub2);
return mergeTwoLists(l1,l2);
}
};