题目:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
直接想法是连接相邻的链表,需要遍历两个链表,复杂度为n,
然后将链表容器遍历一遍,也是n,总时间复杂度为O(n^2)
然后想到O(nlogn)的方法,可以用到归并排序算法
归并算法即递归合并,先用二分法分解,然后合并
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
if(lists.size()==NULL) return NULL;
return merge(lists,0,lists.size()-1);
}
ListNode *merge(vector<ListNode *> &lists,int l,int r){
if(l==r) return lists[l];
int mid=l+(r-l)/2;
ListNode *left=merge(lists,l,mid);
ListNode *right=merge(lists,mid+1,r);
return mergeList(left,right);
}
ListNode *mergeList(ListNode *left,ListNode *right){
if(left==NULL) return right;
if(right==NULL) return left;
if(left->val<right->val){
left->next=mergeList(left->next,right);
return left;
}
else{
right->next=mergeList(left,right->next);
return right;
}
}
};