堆排序,利用优先队列priority_que来做
输入n个整数,输出其中最小的k个
http://www.nowcoder.com/practice/69ef2267aafd4d52b250a272fd27052c
#include <iostream>
#include <vector>
#include <set>
#include<algorithm>
#include<string>
#include<queue>
using namespace std;
int main() {
int n;
while(cin>>n){
int k;
cin>>k;
priority_queue<int>que;//默认是大顶堆
for(int i =0;i<n;i++){
int x;
cin>>x;
if(que.size()<k)que.push(x);
else {
if(x<que.top()){
que.pop();
que.push(x);
}
}
}
vector<int>vet;
while(que.size()>0){
vet.push_back(que.top());
que.pop();
}
reverse(vet.begin(), vet.end());
for(auto c:vet){
cout<<c<<" ";
}
cout<<endl;
}
}
#include <vector>
#include <set>
#include<algorithm>
#include<string>
#include<queue>
using namespace std;
int main() {
int n;
while(cin>>n){
int k;
cin>>k;
priority_queue<int>que;//默认是大顶堆
for(int i =0;i<n;i++){
int x;
cin>>x;
if(que.size()<k)que.push(x);
else {
if(x<que.top()){
que.pop();
que.push(x);
}
}
}
vector<int>vet;
while(que.size()>0){
vet.push_back(que.top());
que.pop();
}
reverse(vet.begin(), vet.end());
for(auto c:vet){
cout<<c<<" ";
}
cout<<endl;
}
}