题目描述
有一个整数数组,请你根据快速排序的思路,找出数组中第K大的数。
给定一个整数数组a,同时给定它的大小n和要找的K(K在1到n之间),请返回第K大的数,保证答案存在。
示例1
输入
[1,3,5,2,2],5,3
返回值
2
import java.util.*;
public class Finder {
public int findKth(int[] a, int n, int K) {
// write code here
//思想:快排+二分法利用快排在排序时,把数组分成两部分
//选temp 值为a[start],经过一轮后 数组左边的值小于或者等于temp,数组右边的所有值都大于或等于temp
//假设此时 i整好等于k,那么temp就是第K大的值
//如果i大于k,那么说明第K大值在数组左边,则继续在左边查找
//如果i小于k,那么说明第K大值在数组的右边,继续在右边查找
return quickSort(a, 0, n - 1, K);
}
public int quickSort(int[] a, int start, int end, int k){
int temp=a[start];
int s=start,e=end;
while(s<e){
while(s<e && temp >=a[e]) e--;
a[s]=a[e];
while(s<e && temp<=a[s]) s++;
a[e]=a[s];
}
a[s]=temp;
if(s==k-1){
return a[s];
}else if(s > k-1){
return quickSort(a, start,s-1,k);
}else{
return quickSort(a, s+1, end, k);
}
}
}
本文介绍如何使用快速排序算法配合二分查找的思想,在给定整数数组中找到第K大的元素。通过实例代码实现`Finder`类,详细解析了查找过程。

503

被折叠的 条评论
为什么被折叠?



