Acwing---786. 第k个数

第k个数

1.题目

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

个数。

输入格式

第一行包含两个整数 n 和 k。

第二行包含 n 个整数(所有整数均在 1∼10^9范围内),表示整数数列。

输出格式

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

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

输入样例:

5 3

2 4 1 5 3

输出样例:

3

2.基本思想

快速排序

3.代码实现

csharp 复制代码
 
import java.io.BufferedInputStream;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(new BufferedInputStream(System.in));
        int n = sc.nextInt();
        int k = sc.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) arr[i] = sc.nextInt();
        qucik_sort(arr, 0, n - 1);
            System.out.println(arr[k-1]);
    }

    private static void qucik_sort(int[] arr, int l, int r) {
        //判断边界
        if (l >= r) return;

        int x = arr[l], i = l - 1, j = r + 1;
        while (i < j) {
            do {
                i++;
            } while (arr[i] < x);
            do {
                j--;
            } while (arr[j] > x);
            //交换
            if (i < j) {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
        //递归子序列
        qucik_sort(arr, l, j);
        qucik_sort(arr, j + 1, r);
    }
}
相关推荐
一只乔哇噻12 分钟前
java后端工程师进修ing(研一版 || day41)
java·开发语言·学习·算法
愚润求学14 分钟前
【贪心算法】day7
c++·算法·leetcode·贪心算法
要开心吖ZSH40 分钟前
软件设计师备考-(十六)数据结构及算法应用(重要)
java·数据结构·算法·软考·软件设计师
逍遥德1 小时前
Java8 Comparator接口 和 List Steam 排序使用案例
java·spring boot·list·排序算法
带娃的IT创业者1 小时前
如何开发一个教育性质的多线程密码猜测演示器
网络·python·算法
zhong liu bin2 小时前
MySQL数据库面试题整理
数据结构·数据库·mysql
Aczone282 小时前
硬件(六)arm指令
开发语言·汇编·arm开发·嵌入式硬件·算法
luckys.one7 小时前
第9篇:Freqtrade量化交易之config.json 基础入门与初始化
javascript·数据库·python·mysql·算法·json·区块链
~|Bernard|8 小时前
在 PyCharm 里怎么“点鼠标”完成指令同样的运行操作
算法·conda
战术摸鱼大师8 小时前
电机控制(四)-级联PID控制器与参数整定(MATLAB&Simulink)
算法·matlab·运动控制·电机控制