思想:priority_queue 底层是由堆实现的,所以使用堆这种数据结构,时间复杂度n*lg(k)(假设n个数据都要调整,且堆的调整复杂度为堆的高度lg(k)),空间复杂度k。
代码如下:
#include<iostream>
#include<stdio.h>
#include<queue>
#include <vector>
using namespace std;
void topk(vector<int> ary, int k) {
priority_queue<int, vector<int>, greater<>> heap; //升序
int i = 0;
while (i < ary.size()) {
if (i < k)
{
heap.push(ary[i]);
} else {
if (heap.top() < ary[i]) {
heap.pop();
heap.push(ary[i]);
}
}
i++;
}
while (!heap.empty()) {
cout << heap.top() << endl;
heap.pop();
}
}
int main() {
int ar[] = { 2,1,4,3,9,8 };
vector<int> vec(begin(ar), end(ar));
topk(vec, 3);
}