题目
C++ solution
/**
* 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) {
int len = lists.size();
if (len == 0) {
return NULL;
}
int interval = 1;
while (interval < len) {
for (int i = 0; i + interval < len; i += interval * 2)
{
lists[i] = mergeTwoLists(lists[i], lists[i+interval]);
}
interval *= 2;
}
return lists[0];
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == NULL) {
return l2;
} else if (l2 == NULL) {
return l1;
}
int min = 0;
if (l1->val < l2->val) {
min = l1->val;
l1 = l1->next;
} else {
min = l2->val;
l2 = l2->next;
}
ListNode* result = new ListNode(min);
ListNode* temp = result;
while (l1 != NULL) {
if (l2 == NULL) {
temp->next = new ListNode(l1->val);
temp = temp->next;
l1 = l1->next;
continue;
}
if (l1->val < l2->val) {
min = l1->val;
l1 = l1->next;
} else {
min = l2->val;
l2 = l2->next;
}
temp->next = new ListNode(min);
temp = temp->next;
}
while (l2 != NULL) {
temp->next = new ListNode(l2->val);
temp = temp->next;
l2 = l2->next;
}
return result;
}
};
简要题解
采用分治算法:
分 - 将合并 k 个有序链表的问题分成合并 2 个有序链表的问题;
治 - 将具有 N 个链表的集合中每 2 个链表合并,生成具有 (N+1)/2 个链表的新集合,迭代直到集合中只有一个链表,该链表即为最终结果。
注:合并 2 个有序链表的方法见上一个博客。