相关问题
Discription
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
思路
最小堆
该题为二路归并的变种,多路归并。使用最小堆结构在
log(k)
时间复杂度内找到当前最小元素。
时间复杂度:
nlog(k)
空间复杂度:
O(n)
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
bool cmp(const ListNode *a, const ListNode *b)
{
return a->val > b->val;
}
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if (lists.empty())
return NULL;
vector<ListNode*> heap;
ListNode *root, *pNode;
for (int i = 0; i < lists.size(); i++)
{
if (lists[i])
heap.push_back(lists[i]);
}
if (heap.empty())
return NULL;
make_heap(heap.begin(), heap.end(), cmp);
pop_heap(heap.begin(), heap.end(), cmp);
pNode = root = heap.back();
heap.pop_back();
while (!heap.empty())
{
// 加入元素
if (pNode->next)
{
heap.push_back(pNode->next);
push_heap(heap.begin(), heap.end(), cmp);
}
// 取出元素
pop_heap(heap.begin(), heap.end(), cmp);
pNode->next = heap.back();
heap.pop_back();
pNode = pNode->next;
}
return root;
}
};