利用快排的思想寻找数组中第K大(小)的数字。举例:给定一个整数数组num,同时给定它的大小n和要找的K(K在1到n之间),请返回第K大的数,保证答案存在。如输入数组[1,3,5,2,2],5,3,返回:2。
解题思路:首先了解快排思想,即每次可以将一个元素放到最终位置上,所以如果当前放置的元素是第K个位置,即得到了最终的结果,不用继续进行排序操作。所以有以下代码。
public class FindKthNum {
private static int findKthNum(int[] num, int len, int k) {
return quickSort(num, 0, len-1, k);
}
private static int quickSort(int[] num, int low, int high, int k){
if(low <= high){
int pos = partition(num, low, high);
if(pos == k-1)
return num[pos];
else if(pos > k-1)
return quickSort(num, low, pos-1, k);
else
return quickSort(num, pos+1, high, k);
}else
return -1;
}
private static int partition(int[] num, int low, int high) {
int tmp = num[low];
while(low < high){
while((low < high) && tmp >= num[high])//(1)
high--;
num[low] = num[high];
while((low < high) && tmp <= num[low])//(2)
low++;
num[high] = num[low];
}
num[low] = tmp;
return low;
}
public static void main(String[] args) {
int[] num = {1,3,5,2,2};
System.out.println(findKthNum(num, 5, 3));
}
}
在上面的代码中,求第K大时在(1)(2)中按从大到小排序、求第K小时在(1)(2)中按从小到大排序,只改变大于号、小于号即可。