第K个数
问题描述:
给定一个长度为n的整数数列,以及一个整数k,请用快速选择算法求出数列从小到大排序后的第k个数。
输入格式
第一行包含两个整数 n 和 k。
第二行包含 n 个整数(所有整数均在1~109范围内),表示整数数列。
输出格式
输出一个整数,表示数列的第k小数。
数据范围
1≤n≤100000,
1≤k≤n
问题分析:
这一道题可以用快排来写,直接对数组进行排序,再输出第个数 ,这样时间复杂度是o(nlogn).有一个优化的方法,根据快排的思想而写的快速选择算法,时间复杂度仅为O(n)。
这个方法和快排不一样的地方在于,快排需要对两个子数组进行排序,而快速选择算法只需要的一个子数组进行排序,看看小于这个数的数量(cnt)。如果(k <= cnt) 则对右边的数进行排序,否者对左边的数进行排序找到第(k - cnt)大的数。
AC代码
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N = 100010;
int q[N];
int n, k;
int quick_sort(int q[], int l, int r, int k) {
if (l >= r) return q[l];
int i = l - 1, j = r + 1, x = q[l + r >> 1];
while (i < j) {
do i ++; while (q[i] < x);
do j --; while (q[j] > x);
if (i < j) swap(q[i], q[j]);
else break;
}
int cnt = j - l + 1;
if (k <= cnt) return quick_sort(q, l, j, k);
else return quick_sort(q, j + 1, r, k - cnt);
}
int main() {
scanf("%d%d", &n, &k);
for (int i = 0; i < n; i ++)
scanf("%d", &q[i]);
cout << quick_sort(q, 0, n - 1, k) << endl;
return 0;
}