博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
优先队列实现n路归并算法O(n * lgK)
阅读量:7227 次
发布时间:2019-06-29

本文共 1727 字,大约阅读时间需要 5 分钟。

//problem description: merge K sorted lists with total N elements

//solution: put the front element of each list into a priority queue,
// till finish, pop the min value from the priority queue, and enqueue
// the next element in corresponding list, delete that element
//time complexity:
// select min value in the queue with K elements: O(lgK)
// repeat O(n) times
// time complexity = O(n * lgK)
//space complexity:
// output array = O(n)
// priority queue = O(k)
// space complexity = O(n + k) = O(n)
#include <queue>
#include <list>
#include <vector>
#include <iostream>
using namespace std;

//support compare function for priority heap

struct Comparator
{
bool operator()(const list<int>*a, const list<int>*b) const
{
if(b->size() == 0)
return false;
return a->front() > b->front();
}
};

vector<int> nWayMerge(list<list<int> >& l)

{
vector<int> output;
priority_queue<list<int>*, vector<list<int>* >, Comparator> q;
list<list<int> >::iterator iter;
//initialize the priority queue by
//putting each list
//into the queue
for(iter = l.begin(); iter != l.end(); iter++)
q.push(&*iter);
//once the min list goes empty,
//we know all elements has been dealed
while(q.top()->size() != 0)
{
//pop the min element in the queue
output.push_back(q.top()->front());
q.top()->pop_front();
list<int>* l = q.top();
q.pop();
q.push(l);
}
return output;
}
int main()
{
//test cases with 3 sorted lists
list<list<int> > input;
list<int> l1 = {12, 15, 16, 18, 20};
list<int> l2 = {11, 13, 18, 20, 22};
list<int> l3 = {9, 14, 15, 20, 23};
input.push_back(l1);
input.push_back(l2);
input.push_back(l3);
vector<int> v = nWayMerge(input);
for(vector<int>::iterator iter = v.begin(); iter != v.end(); iter++)
cout << *iter << endl;
return 0;
}

转载地址:http://rebfm.baihongyu.com/

你可能感兴趣的文章
面试题系列一之 程序生命周期
查看>>
设计模式——观察者模式:气象监测应用
查看>>
NSUserDefaults简介及如何使用 NSUserDefaults 存储自定义对象
查看>>
IntelliJ IDEA搭建SpringBoot
查看>>
深入浅出iOS事件机制
查看>>
hadoop理解
查看>>
Oracle——18用户、角色和权限信息的视图总结
查看>>
WordPress 中的 Debug 模式(调试模式)
查看>>
node下使用express框架,ejs模板引擎
查看>>
搜索:文本的匹配算法
查看>>
Fedora 17 LibreOffice 办公套件的安装与汉化
查看>>
scrollview不充满屏幕的原因
查看>>
PHP单例模式
查看>>
解密敏捷自动化测试
查看>>
DelphiMVC拦截器介绍
查看>>
Spring Cloud构建微服务架构:分布式配置中心【Dalston版】
查看>>
iOS 11正式版终于来了!强力助攻小程序
查看>>
开放平台API接口调用频率控制系统设计浅谈
查看>>
Lucene4.3进阶开发之潜龙勿用( 七)
查看>>
DTD和schema小总结
查看>>