题目描述:
合并 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) {
multimap<int, ListNode*> headMap;
for (ListNode* l : lists)
{
if (l != NULL)
headMap.insert(pair<int, ListNode*>(l->val, l));
}
ListNode dummy(0);
ListNode* tail = &dummy;
while (!headMap.empty())
{
multimap<int, ListNode*>::iterator iterator = headMap.begin();
tail->next = iterator->second;
tail = tail->next;
if (iterator->second->next != NULL) headMap.insert(pair<int, ListNode*>(iterator->second->next->val, iterator->second->next));
headMap.erase(iterator);
}
tail->next = NULL;
return dummy.next;
}
};