wordpress的语言/seo门户网站
【问题描述】
给定一个序列,找出序列中最大的K个数或者最小的K个数,称为topK问题。
【算法分析】
只需将“第K大元素”问题(https://blog.csdn.net/hnjzsyjyj/article/details/119813940)中的代码cout<<L.top()<<" "; 修改为如下代码便可。即:
while(!L.empty()){cout<<L.top()<<" ";L.pop();
}
完整的“topK 问题”算法代码如下所示。
【算法代码】
#include<bits/stdc++.h>
using namespace std;priority_queue<int,vector<int>,greater<int> > L; //Small Root Heapint main() {int k;cin>>k;vector<int> v;int x;while(cin>>x) {v.push_back(x);}for(int i=0; i<v.size(); i++) {if(L.size()<k) {L.push(v[i]);} else if (v[i]>L.top()) {L.pop();L.push(v[i]);}}while(!L.empty()) {cout<<L.top()<<" ";L.pop();}return 0;
}/*
in:
3
3 2 7 5 8 1
out:
5 7 8
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/119813940