码迷,mamicode.com
首页 > 编程语言 > 详细

第k小数(桶排序)

时间:2020-05-25 22:10:54      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:tar   its   pre   ref   har   style   code   std   color   

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;

 

第k小数(桶排序)

标签:tar   its   pre   ref   har   style   code   std   color   

原文地址:https://www.cnblogs.com/mohari/p/12961032.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!