题目描述
有一个整数数组,请你根据快速排序的思路,找出数组中第K大的数。
给定一个整数数组a,同时给定它的大小n和要找的K(K在1到n之间),请返回第K大的数,保证答案存在。
测试样例:
[1,3,5,2,2],5,3返回:2
import java.util.*;
public class Finder {
public int findKth(int[] a, int n, int K) {
quickSort(a,0,a.length-1);
return a[n-1-K+1];
}
//快排
public void quickSort(int[] a,int low,int high){
if(low > high){
return;
}
int i = low;
int j = high;
int temp = a[low];
while (i<j){
while (i<j && temp <= a[j]){
j--;
}
while (i<j && temp >= a[i]){
i++;
}
if(i<j){
int tmp = a[j];
a[j] = a[i];
a[i] = tmp;
}
}
a[low] = a[j];
a[i] = temp;
quickSort(a,low,j-1);
quickSort(a,j+1,high);
}
}