(STL)nth_element
zzr8178541919 · · 个人记录
nth_element是
它可以在不需排序的条件下,快速地访问第k小的值,时间复杂度是线性的。
有的时候非常方便。
使用(数组的下标从0开始):
nth_element(a,a+k,a+n)
函数把下标为
这样我们只需访问
应用:
求区间第
#include<bits/stdc++.h>
//#define int long long
#define reg register
using namespace std;
const int maxn=5e6+5;
const int mod=1e9+7;
const int INF=2e9;
inline int read()
{
int x=0,f=1;
char ch=getchar();
while(ch<'0' || ch>'9')
{
if(ch=='-')
f=-1;
ch=getchar();
}
while(ch>='0' && ch<='9')
{
x=x*10+ch-'0';
ch=getchar();
}
return x*f;
}
int a[maxn];
int n,k;
signed main()
{
n=read(),k=read();
for(int i=0;i<n;i++)
a[i]=read();
nth_element(a,a+k,a+n);
printf("%d\n",a[k]);
return 0;
}
/*
10 4
5 4 3 4 2 2 3 2 6 1 7
*/