没啥说的:top k大 用小跟堆; top k小 用大根堆
优先级队列默认 使用 大根堆 可以求top K小
上代码:
求Top K大
#include<iostream>
#include <queue> priority_queue
#include <ctime>
#include <functional> greater less
using namespace std;
int main()
{
vector<int> vec;
srand(time(NULL));
for (int i = 0; i < 1000000; ++i)//先插入1000000个数
{
vec.push_back(rand()%1000000 + 1);
}
vec.push_back(40000);
//priority_queue<int> queue2; 使用优先级对列,默认是大根堆 求top K小
priority_queue<int, vector<int>, greater<int>> queue; 调整为小根堆 求top K大
for (int i = 0; i < 10 ; ++i)
{
queue.push(vec[i]);
}
for (int i = 10; i < vec.size(); ++i)
{
if (vec[i] > queue.top())
{
queue.pop();
queue.push(vec[i]);
}
}
// O(n) * O(log210) = O(n) O(2n)
while (!queue.empty())
{
cout << queue.top() << " ";
queue.pop();
}
cout << endl;
}