zoukankan      html  css  js  c++  java
  • 优先队列实现n路归并算法O(n * lgK)

    //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;
    }

  • 相关阅读:
    [Java] Hibernate
    python基础(十三):函数(一)公共操作
    python基础(十二):数据结构(五)集合
    python基础(十二):数据结构(四)字典
    python基础(十一):数据结构(三)元组
    python基础(十):数据结构(二)列表
    python基础(八):流程控制(五)循环
    python基础(七):流程控制(一)if
    python基础(六):运算符
    python基础(五):转换数据类型
  • 原文地址:https://www.cnblogs.com/mfryf/p/2677759.html
Copyright © 2011-2022 走看看