您的位置:首页 > 编程语言 > C语言/C++

LeetCode 22. Merge k Sorted Lists

2014-06-16 04:12 435 查看
用一个最小堆盛放所有有序链表的头结点即可。

复杂度O(nlogm) -- n为结点总数,m为vector.size()

代码:

class Solution
{
public:
struct cmp
{
bool operator () (const ListNode* a, const ListNode* b)
{
return a->val > b->val;
}
};
ListNode *mergeKLists(vector<ListNode *> &lists)
{
ListNode *head=NULL, *cur=NULL;
priority_queue<ListNode*, vector<ListNode*>, cmp> ss;

for (auto it = lists.begin(); it != lists.end(); ++ it)
{
if (*it != NULL)
{
ss.push(*it);
}
}
while(ss.empty() == false)
{
auto top = ss.top();
if (head == NULL)
{
head = cur = top;
} else
{
cur->next = top;
cur = cur->next;
}
ss.pop();
if (top->next != NULL)
{
ss.push(top->next);
}
}

return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息