您的位置:首页 > 其它

Leetcode -- Merge k Sorted Lists

2015-10-23 20:39 239 查看
Merge k sorted
linked lists and return it as one sorted list. Analyze and describe its complexity.

本题使用优先队列,自定义优先级。

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
struct cmp
{
bool operator ()(pair<int,int> &a,pair<int,int> &b)
{
return a.first>b.first;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode *h = new ListNode(-1),*p = h;
priority_queue<pair<int,int>,vector<pair<int,int> >,cmp> que;
int n = lists.size();
for(int i=0;i<n;++i)
if(lists[i])
{
que.push(make_pair(lists[i]->val,i));
}

while(!que.empty())
{
auto tmp = que.top();
que.pop();
int val = tmp.first,idx = tmp.second;
p->next = lists[idx];
lists[idx] = lists[idx]->next;
if(lists[idx])
{
que.push(make_pair(lists[idx]->val,idx));
}
p = p->next;
}
p = h->next;
delete h;
return p;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: