Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Subscribe to see which companies asked this question.
要求将k个已排序的链表合并成一个排序的链表。用priority_queue实现,优先队列中保存链表节点,节点值小的优先。首先将所有的链表的头结点push进队列。然后对队列进行操作,每次取队列的top项(还要pop出来),这是当前值最小的节点,将它连接在结果链表的后端,如果该节点还有后续节点,把后续节点push进队列中。循环上述操作直到优先队列为空。
代码:
class Solution
{
public:
ListNode* mergeKLists(vector<ListNode*>& lists)
{
if(lists.empty()) return NULL;
auto cmp = [](const ListNode* n1, const ListNode* n2){ return n1->val > n2->val; };
priority_queue<ListNode*, vector<ListNode*>, function<bool (const ListNode*, const ListNode*)> >pq(cmp);
for(auto list:lists)
{
if(list)
{
pq.push(list);
}
}
if(pq.empty()) return NULL;
ListNode* res = NULL, * prev, * cur;
while(!pq.empty())
{
cur = pq.top();
pq.pop();
if(cur->next) pq.push(cur->next);
if(!res)
{
res = cur;
}
else
{
prev->next = cur;
}
prev = cur;
}
prev->next = NULL;
return res;
}
};