You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

AcWing 786. 第k个数

一、题目描述

给定一个长度为 n 的整数数列,以及一个整数 k,请用快速选择算法求出数列从小到大排序 后的第 k 个数。

输入格式 第一行包含两个整数 nk

第二行包含 n 个整数(所有整数均在 1109 范围内),表示整数数列。

输出格式 输出一个整数,表示数列的第 k 小数。

数据范围 1≤n≤100000,1≤k≤n

输入样例:

5 3
2 4 1 5 3

输出样例:

3

二、理解感悟

1、这是快速排序模板的练习题。

2、不一样的地方在于它可以利用快排模板但却不需要真的把所有数据排序完成每次一分为二后只关心自己所有的那一半就是可以节约一半的递归时间。

3、由于是关心 位置(第几个),所以在递归时需要携带这个参数。

4、位置这个参数 不是一成不变的,因为如果在左侧,那么就是原来的位置,如果在右侧,那就需要减去整个左侧的长度。这个 k参数可以理解为 在当前数组中的位置,最终将确定这个位置上的值。

5、最后直接使用q[k]就是拿到了最终这个位置上应该存在的值。

三、实现代码

#include <bits/stdc++.h>

using namespace std;
const int N = 100010;
int q[N];
int n, k;

void quick_sort(int q[], int l, int r, int k) {
    if (l >= r) return;
    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]);
    }
    int len = j - l + 1; // 左侧长度
    if (k <= len)
        quick_sort(q, l, j, k); // 左侧
    else
        quick_sort(q, j + 1, r, k - len); // 右侧
}

int main() {
    cin >> n >> k;
    for (int i = 1; i <= n; i++) cin >> q[i];
    quick_sort(q, 1, n, k);
    printf("%d", q[k]);
    return 0;
}