AcWing 786. 第k个数
原题链接
简单
作者:
理想二旬.
,
2021-05-01 22:10:22
,
所有人可见
,
阅读 258
JAVA 代码
import java.util.Scanner;
import java.io.BufferedInputStream;
class Main{
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedInputStream(System.in));
int n = in.nextInt();
int q = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
MergeSort(arr, 0, n - 1);
System.out.println(find(arr, q - 1));
}
public static int find(int[] arr, int k){
return arr[k];
}
public static void quickSort(int[] arr, int l, int r){
if(l >= r)
return;
//1. 确定分界点
int x = arr[l];
int i = l - 1, j = r + 1;
//2. 分区间
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;
}
}
//3. 递归
quickSort(arr, l, j);
quickSort(arr, j + 1, r);
}
public static void MergeSort(int[] arr, int l, int r){
if(l >= r)
return;
//0. 确定分界点---取中点
int mid = l + r >> 1;
//1. 递归排序左边和右边
MergeSort(arr, l, mid);
MergeSort(arr, mid + 1, r);
//2. 归并---将两个有序数组合并成一个有序数组---双指针算法
//对两个数组分别取头指针,不断比较两个指针大小,在开辟一个新数组容纳
int[] temp = new int[r - l + 1];
int k = 0;//表示当前temp一共有多少个数
int i = l,j = mid + 1 ;//两个指针
while(i <= mid && j <= r){
if(arr[i] <= arr[j])
temp[k++] = arr[i++];
else
temp[k++] = arr[j++];
}
while(i <= mid)
temp[k++] = arr[i++];
while(j <= r)
temp[k++] = arr[j++];
for (i = l, j = 0; i <= r; i++, j++)
arr[i] = temp[j];
}
}