跳到正文

个人记录

(STL)nth_element

zzr8178541919约 2 分钟
原文
文章信息与版本

文章信息

发布
2021年1月18日
收录
2025年12月12日
更新
2026年11月21日
篇幅
约 2 分钟

版本

  1. v1当前

nth_element是stlstl中自带的一个函数。

它可以在不需排序的条件下,快速地访问第k小的值,时间复杂度是线性的。

有的时候非常方便。

使用(数组的下标从0开始):

C++
nth_element(a,a+k,a+n)

函数把下标为kk的元素放在了正确位置,对其它元素并没有排序,同时使得kk左边元素都小于等于它,右边元素都大于等于它。

这样我们只需访问a[k]a[k]就能得到想要的元素。

应用:

求区间第kk小值:P1923 【深基9.例4】求第 k 小的数

code:code:

C++
#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 
*/
原文