Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
翻译
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
分析
两两归并排序。每次排序复杂度O(2n),n为链表长度。一共要排序(n/2+n/4+…+1) = n次。所以复杂度是O(n^2)。
c++实现
/**
* 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) {
if (lists.size() == 0)
return NULL;
merge(lists,lists.size());
return lists[0];
}
void merge(vector<ListNode*>& lists,int size) {
if (size == 1)
return;
for (int i = 0; i < size/2; i++)
{
ListNode* tmp = zuhe(lists[i],lists[size-1-i]);
lists.push_back(tmp);
}
if (size&1)
lists.push_back(lists[size/2]);
vector<ListNode*>:: iterator it = lists.begin();
lists.erase(it,it+size);
merge(lists,lists.size());
}
ListNode* zuhe(ListNode* l1,ListNode* l2) {
ListNode* l = new ListNode(0);
ListNode* head = l;
while (l1 || l2)
{
if (!l1)
{
l->next = l2;
l2 = l2->next;
l = l->next;
}
else if (!l2)
{
l->next = l1;
l1 = l1->next;
l = l->next;
}
else
{
if (l1->val <= l2->val)
{
l->next = l1;
l1 = l1->next;
l = l->next;
}
else
{
l->next = l2;
l2 = l2->next;
l = l->next;
}
}
}
return head->next;
}
};