Merge k Sorted Lists[hard]
[题目]
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
显然,这道题是在上周所做Merge Two Sorted Lists那道题的基础上将K个已经排序了的链表合并。
[解]
我们很容易的想到我们上课所学到的分治算法。
我们可以两个两个的进行合并,直至最后只剩下一个链表。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
while (lists.empty()) return NULL;
while (lists.size() > 1) {
lists.push_back(mergeTwoLists(lists[0], lists[1]));
lists.erase(lists.begin());
lists.erase(lists.begin());
}
return lists.front();
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* head = new ListNode(INT_MIN);
ListNode* t = head;
while (l1 && l2) {
if (l1->val < l2->val) {
t->next = l1;
t = t->next;
l1 = l1->next;
} else {
t->next = l2;
t = t->next;
l2 = l2->next;
}
}
if (l1 == NULL&&l2 != NULL) {
t->next = l2;
}
if (l1 != NULL&&l2 == NULL) {
t->next = l1;
}
return head->next;
}
};