站外题求助dalao第k大数(n<=1e7)
  • 板块灌水区
  • 楼主ZYH20190341315
  • 当前回复10
  • 已保存回复10
  • 发布时间2021/5/10 23:30
  • 上次更新2023/11/4 23:24:52
查看原帖
站外题求助dalao第k大数(n<=1e7)
400760
ZYH20190341315楼主2021/5/10 23:30

优先队列和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;
}
2021/5/10 23:30
加载中...