合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
暴力法:
1.全部加入到数组里面。
2.快速排序。
3.重新构建链表
#include <iostream>
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
vector<int> res;
for(int i=0;i<lists.size();i++){
ListNode*head = lists[i];
while(head!=NULL){
res.push_back(head->val);
head = head->next;
}
}
QS(res,0,res.size()-1);
ListNode *head = new ListNode(0);
ListNode *tail = head;
for(int i=0;i<res.size();i++){
ListNode *tmp = new ListNode(res[i]);
tail->next = tmp;
tail = tmp;
}
head = head->next;
return head;
}
public:
void QS(vector<int>& a,int left,int right){
if(left>=right){
return;
}
int i = left;
int j = right;
int key = a[left];
while(i<j){
while(i<j && key<=a[j]){
j--;
}
a[i] = a[j];
while(i<j && key>=a[i]){
i++;
}
a[j] = a[i];
}
a[i] = key;
QS(a,left,i-1);
QS(a,i+1,right);
}
};
int main(){
Solution *ps = new Solution();
ListNode *t1 = new ListNode(1);
ListNode *t2 = new ListNode(4);
ListNode *t3 = new ListNode(5);
ListNode *l1 = new ListNode(1);
ListNode *l2 = new ListNode(3);
ListNode *l3 = new ListNode(4);
ListNode *m1 = new ListNode(2);
ListNode *m2 = new ListNode(6);
t1->next = t2;
t2->next = t3;
l1->next = l2;
l2->next = l3;
m1->next = m2;
vector<ListNode *> vec;
vec.push_back(t1);
vec.push_back(l1);
vec.push_back(m1);
ListNode *res = ps->mergeKLists(vec);
while(res!=NULL){
cout<<res->val<<endl;
res = res->next;
}
return 0;
}