合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
/**
* 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 nullptr;
}
if(lists.size() == 1)
{
return lists[0];
}
if(lists.size() == 2)
{
return merge2Lists(lists[0],lists[1]);
}
size_t list_num = lists.size();
size_t n1 = list_num/2;
size_t n2 = list_num - n1;
vector<ListNode*> lists_sub1;
vector<ListNode*> lists_sub2;
int i=0;
while(n1)
{
lists_sub1.push_back(lists[i]);
i++;
n1--;
}
while(n2)
{
lists_sub2.push_back(lists[i]);
i++;
n2--;
}
ListNode* head1 = mergeKLists(lists_sub1);
ListNode* head2 = mergeKLists(lists_sub2);
return merge2Lists(head1,head2);
}
ListNode* merge2Lists(ListNode* l1, ListNode* l2)
{
ListNode temNode(0);
ListNode* pCurNode = &temNode;
while(l1 && l2)
{
if(l1->val <= l2->val)
{
pCurNode->next = l1;
l1 = l1->next;
}
else
{
pCurNode->next = l2;
l2 = l2->next;
}
pCurNode = pCurNode->next;
}
if(l1)
{
pCurNode->next = l1;
}
if(l2)
{
pCurNode->next = l2;
}
return temNode.next;
}
};