AcWing 786. 第k个数
原题链接
简单
作者:
恒心
,
2020-10-21 01:36:08
,
所有人可见
,
阅读 332
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] nums = new int[n];
for(int i = 0; i < n; ++i){
nums[i] = sc.nextInt();
}
System.out.println(findK(nums, 0, n - 1, k - 1));
}
public static int findK(int[] nums, int start, int end, int k){
int left = start, right = end;
int x = nums[left + (right - left)/2];
while(left <= right){
while (left <= right && nums[left] < x) {
left++;
}
while (left <= right && nums[right] > x) {
right--;
}
if(left <= right){
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
if(k <= right) {
return findK(nums, start, right, k);
}else if(k >= left){
return findK(nums, left, end, k);
}else{
return nums[k];
}
}
}