第k小数--牛客

题目:
给你一个长度为n的序列,求序列中第k小数的多少。
输入描述:
链接:第k小数–牛客
来源:牛客网

多组输入,第一行读入一个整数T表示有T组数据。每组数据占两行,第一行为两个整数n,k,表示数列长度和k。第二行为n个用空格隔开的整数。
输出描述:
对于每组数据,输出它的第k小数是多少。每组数据之间用空格隔开。
示例1
输入:
2
5 2
1 4 2 3 4
3 3
3 2 1
输出:
2
3

思路: 这道题可能会有大量的输入数据,普通的输入可能会超时,这道题需要用到快读和nth_element()函数。
快排:

#define re register
inline int read()
{
    re int x=0,f=1;
    re char ch=getchar();
    while(ch<'0'||ch>'9') {if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+(ch^48),ch=getchar();
    return x*f;
}

nth_element函数
用法:
nth_element(start,start+k,end)
使得第k大的数安排在下标为k的数组上。

代码如下:

#include <iostream>
#include <algorithm>
using namespace std;
#define re register
inline int read()
{
    re int x=0,f=1;
    re char ch=getchar();
    while(ch<'0'||ch>'9') {if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+(ch^48),ch=getchar();
    return x*f;
}
int main()
{
 const int maxn=5e6+5;
 int i,t,n,k,a[maxn];
 cin>>t;
 while(t--)
 {
  n=read();
        k=read();
  for(i=1;i<=n;i++)
  {
   a[i]=read();
  }
  nth_element(a,a+k,a+n+1);
  cout<<a[k+1]<<endl;
 }
 return 0;
}
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值