Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
这道题是要求归并k个有序单链表。
采用分治法,将任务分成两个子任务,然后递归求子任务,最后回溯:将k个list分成两半,然后继续划分,剩余连个list就合并。
/**
* 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* h1 = l1;
ListNode* h2 = l2;
ListNode* ans = new ListNode(0);
ListNode* l3 = ans;
while (h1&&h2){
if (h1->val <= h2->val){
ans->next = h1;
ans = h1;
h1 = h1->next;
}
else{
ans->next = h2;
ans = h2;
h2 = h2->next;
}
}
ans->next = h1 ? h1 : h2;
return l3->next;
}
ListNode *mergeKLists(vector<ListNode *> &lists) {
int len = lists.size();
if (!len)
return NULL;
int count = 1;
while (len>1){
for (int i = 0; i < lists.size()-count; i += (count*2)){
lists[i] = mergeTwoLists(lists[i], lists[i + count]);
}
count*=2;
len = len / 2 + len%2;
}
return lists[0];
}
};