题目描述:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
对k个链表进行二分处理,两个一组进行归并,时间复杂度为O(log(k)* n)。
关于时间复杂度的分析看这里:Merging k sorted linked lists - analysis
代码:
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
if (lists.empty())
return NULL;
return mergeSort(lists, 0, lists.size() - 1);
}
ListNode *mergeSort(vector<ListNode*> &lists, int l, int r){
if (l > r)
return NULL;
if (l == r)
return lists[l];
ListNode *left = mergeSort(lists, l, l + (r - l) / 2);
ListNode *right = mergeSort(lists, l + (r - l) / 2 + 1, r);
ListNode *res = new ListNode(0);
ListNode *node = res;
while (left || right){
if (!left){
node->next = right;
break;
}
if (!right){
node->next = left;
break;
}
if (left->val < right->val){
node->next = left;
left = left->next;
}
else{
node->next = right;
right = right->next;
}
node = node->next;
}
return res->next;
}
};