瑶瑶的第K大 (快排+选择一半快排)

瑶瑶的第K大
Time Limit: 4000/2000MS (Java/Others)Memory Limit: 256000/128000KB (Java/Others)
SubmitStatisticNext Problem
Problem Description

一天,萌萌的妹子--瑶瑶(tsyao)很无聊,就来找你玩。可是你们都不知道玩什么。。。尴尬了一阵子,机智的瑶瑶就提议:“这样吧,你说N个整数xi,然后在随意说一个数字k,我能够快速地说出这些数字里面第 k 大的数字。”
Input

第1行 两个整数N, K以空格隔开;

第2行 有N个整数(可出现相同数字,均为随机生成),同样以空格隔开。

0 < n ≤ 5*10^6 , 0 < k ≤ n

1 ≤ xi ≤ 10^8
Output
输出第 k 大的数字。
Sample Input

5 2
5 4 1 3 1

Sample Output

4

Hint
如2,2,1中三个数字中第一大数字为2,第二大数字也为2,第三大数字为1 。
Source
tsyao
Manager
tsyao


#include <iostream>
#include <algorithm>
#include <string>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include<map>
#include<queue>
using namespace std;
const int maxn=100001;
const int base=31700;
const int INF=9999999;
const int MIN=-INF;
int a[5000005];
int n, k, ans;
int read ()
{
    int x = 0;
    char ch = ' ';
    while (ch < '0' || ch > '9')
        ch = getchar ();
    while (ch >= '0' && ch <= '9')
        x = x * 10 + ch - '0', ch = getchar ();
    return x;
}
void sort (int l, int r)
{
    int last = l;
    swap (a[l], a[(l + r) >> 1]);
    for (int i = l + 1; i <= r; ++ i)
        if (a[l] < a[i])
            swap (a[++ last], a[i]);
    swap (a[l], a[last]);
    if (last == k)
        ans = a[k];
    else if (k < last)
        sort (l, last - 1);
    else
        sort (last + 1, r);
}
int main()
{
    int m,i,j,t;
     while (~scanf ("%d%d", &n, &k))
    {
        for (int i = 1; i <= n; ++ i)
            a[i] = read ();
        sort (1, n);
        printf ("%d\n", ans);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值