优先队列和sort都超时20%T_T
在数组中找到从小到大排序后第k大的元素。
第一行输入数组长度n(n<=10000000) 和 1<=k<=n. 第二行输入n个数字。
输出数组中第k个最大的元素。
6 2
3 2 1 5 6 4
5
求个思路
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
int read()
{
char ch=' ';
int ans=0;
while(ch<'0' || ch>'9')
ch=getchar();
while(ch<='9' && ch>='0')
{
ans=ans*10+ch-'0';
ch=getchar();
}
return ans;
}
void out(int a)
{
if(a > 9)
{
out(a/10);
}
putchar(a%10 + '0');
}
int main()
{
int n,k,x;
priority_queue<int,vector<int>,greater<int> > q;
scanf("%d%d",&n,&k);
for(int i=0;i<n;i++)
{
x=read();
if (q.size() != k)
{
q.push(x);
}
else if (q.top() < x)
{
q.pop();
q.push(x);
}
}
out(q.top());
return 0;
}