第k小数(桶排序)

https://ac.nowcoder.com/acm/contest/5773/A

给一个数列,求第k小的数。

一开始想的是集合、优先队列,自动排好序的容器。交上去两个都t了。

换一种思路,用个桶排序,每次遇到一个数加1,从小到大扫一遍,每遇到数列里的数计数加一,等于k时输出。

#include<bits/stdc++.h>
using namespace std;
const int maxn=5e6;
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<<1) + (x<<3) + (ch^48);
        ch = getchar();
    }
    return x * f;
}
int s[maxn+5];
int main(){
    int m,n,k,t;
    t=read();
    for(int i=0;i<t;i++){
        n=read();
        k=read();
        fill(s,s+maxn,0);
        for(int j=0;j<n;j++){
            m=read();
            s[m]++;
        }
        int cnt=0;
        for(int o=1;o<=maxn;o++){
            while(s[o]){
                s[o]--;cnt++;
                if(cnt==k){cout<<o<<endl;break;}
            }
        }
    }
    return 0;

猜你喜欢

转载自www.cnblogs.com/mohari/p/12961032.html
今日推荐