地址:https://leetcode-cn.com/problems/merge-k-sorted-lists/
思路:一、每次比较k个链表的大小,在取最小的
二、利用优先队列可优化每次k个链表的比较
Code:
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/*
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode *head=NULL,*p,*pi;
int INF=-1e9,Min=INF,t,n=lists.size();
for(int i=0;i<n;++i)
{
pi=lists[i];
if(pi!=NULL&&(Min==INF||pi->val<Min)){
Min=pi->val; t=i;
}
}
if(Min!=INF){
p=head=lists[t]; lists[t]=lists[t]->next;
}
while(true){
Min=INF;
for(int i=0;i<n;++i)
{
pi=lists[i];
if(pi!=NULL&&(Min==INF||pi->val<Min)){
Min=pi->val; t=i;
}
}
if(Min!=INF){
p=p->next=lists[t];
lists[t]=lists[t]->next;
}else break;
}
return head;
}
};
*/
//优先队列
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode *head=NULL,*p;
priority_queue<pair<int,ListNode*>,vector<pair<int,ListNode*>>,greater<pair<int,ListNode*>>> Q;
int n=lists.size();
for(int i=0;i<n;++i)
if(lists[i]!=NULL){
Q.push({lists[i]->val,lists[i]});
}
pair<int,ListNode*> pr;
if(!Q.empty()){
pr=Q.top(); Q.pop();
p=head=pr.second;
pr.second=pr.second->next;
if(pr.second!=NULL){
pr.first=pr.second->val;
Q.push(pr);
}
}
while(!Q.empty()){
pr=Q.top(); Q.pop();
p=p->next=pr.second;
pr.second=pr.second->next;
if(pr.second!=NULL){
pr.first=pr.second->val;
Q.push(pr);
}
}
return head;
}
};
int main()
{
return 0;
}