社区讨论

站外题求助dalao第k大数(n<=1e7)

灌水区参与者 6已保存回复 10

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
10 条
当前快照
1 份
快照标识符
@loccv0bs
此快照首次捕获于
2023/10/30 11:43
2 年前
此快照最后确认于
2023/11/04 23:24
2 年前
查看原帖
优先队列和sort都超时20%T_T
在数组中找到从小到大排序后第k大的元素。
第一行输入数组长度n(n<=10000000) 和 1<=k<=n. 第二行输入n个数字。
输出数组中第k个最大的元素。
6 2
3 2 1 5 6 4
5
求个思路
CPP
#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;
}

回复

10 条回复,欢迎继续交流。

正在加载回复...