【模板】第 K 大数

题目:给定一个序列,求其第 K 大的数是多少。

时间复杂度\(O(n)\)

代码如下:

#include <bits/stdc++.h>
using namespace std;
const int maxn=5e6+10;

inline int read(){
    int x=0,f=1;char ch;
    do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch));
    do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch));
    return f*x;
}

int n,k,a[maxn];

int k_th(int l,int r,int k){
    if(l==r)return a[l];
    int tmp=a[l],i=l,j=r;
    while(i<j){
        while(i<j&&a[j]>=tmp)j--;
        while(i<j&&a[i]<=tmp)i++;
        if(i<j)swap(a[i],a[j]);
    }
    swap(a[l],a[i]);
    if(r-i>=k)return k_th(i+1,r,k);
    else return k_th(l,i,k-r+i);
}

int main(){
    n=read(),k=read();
    for(int i=1;i<=n;i++)a[i]=read();
    printf("%d\n",k_th(1,n,k));
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/wzj-xhjbk/p/9845445.html
今日推荐