牛客网 NC207028 第k小数#
目录#
1. 题目描述#
1.1. Limit#
Time Limit: C/C++ 3秒,其他语言6秒
Memory Limit: C/C++ 262144K,其他语言524288K
1.2. Problem Description#
给你一个长度为n的序列,求序列中第k小数的多少。
1.3. Input#
多组输入,第一行读入一个整数 表示有 组数据。
每组数据占两行,第一行为两个整数 ,表示数列长度和 。
第二行为 个用空格隔开的整数。
1.4. Output#
对于每组数据,输出它的第 小数是多少。每组数据之间用空格隔开
1.5. Sample Input#
2
5 2
1 4 2 3 4
3 3
3 2 1
1.6. Sample Output#
2
3
1.7. Note#
,数列里每个数都在int
范围内。
由于输入比较多,请使用快读读取。例如:
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;
}
1.8. Source#
2. 解读#
数据太大了,用STL
中的nth_element()
函数可以通过,sort()
和partial_sort()
都会超时。
3. 代码#
#include <algorithm>
#include <iostream>
using namespace std;
const int NUM = 5e6 + 1;
int list[NUM];
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;
}
// #define DEBUG
int main()
{
#ifdef DEBUG
freopen("debug/test.txt", "r", stdin);
freopen("debug/result.txt", "w", stdout);
#endif // DEBUG
int t, n, k;
scanf("%d", &t);
while (t--) {
scanf("%d %d", &n, &k);
for (int i = 0; i < n; i++) {
list[i] = read();
}
// 将第k小的数放在 k-1 位置,左边的数都比它小,右边的数都比它大,但都是无序的
nth_element(list, list + k - 1, list + n);
// 由于数据量太大,下面两种方法会超时
// 快速排序
// sort(list, list + n);
// 将第k小的数放在 k-1 位置,左边的数都比它小,而且是有序的,右边的数都比它大,但右边是无序的
// partial_sort(list, list + k - 1, list + n);
printf("%d\n", list[k - 1]);
}
return 0;
}
联系邮箱:curren_wong@163.com
CSDN:https://me.csdn.net/qq_41729780
知乎:https://zhuanlan.zhihu.com/c_1225417532351741952
公众号:复杂网络与机器学习
欢迎关注/转载,有问题欢迎通过邮箱交流。