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);
    }
}
相关推荐
mit6.8246 小时前
bfs|栈
算法
CoderYanger7 小时前
优选算法-栈:67.基本计算器Ⅱ
java·开发语言·算法·leetcode·职场和发展·1024程序员节
jllllyuz7 小时前
Matlab实现基于Matrix Pencil算法实现声源信号角度和时间估计
开发语言·算法·matlab
稚辉君.MCA_P8_Java7 小时前
DeepSeek 插入排序
linux·后端·算法·架构·排序算法
多多*8 小时前
Java复习 操作系统原理 计算机网络相关 2025年11月23日
java·开发语言·网络·算法·spring·microsoft·maven
.YM.Z9 小时前
【数据结构】:排序(一)
数据结构·算法·排序算法
Chat_zhanggong3459 小时前
K4A8G165WC-BITD产品推荐
人工智能·嵌入式硬件·算法
百***48079 小时前
【Golang】slice切片
开发语言·算法·golang
墨染点香9 小时前
LeetCode 刷题【172. 阶乘后的零】
算法·leetcode·职场和发展
做怪小疯子9 小时前
LeetCode 热题 100——链表——反转链表
算法·leetcode·链表