实现逻辑:创建一个长度为k的新数组tempHeap,拷贝原数组的前k个元素,然后进行小根堆化,便得到了一个长度为k的小根堆数组。遍历原数组arr的剩余元素,与小根堆数组的第一个元素进行比较,如果原数组中的元素大于小根堆数组的第一个元素,则拷贝该原数组元素到tempHeap[0]上,然后小根堆化,直到遍历完成,最终返回tempHeap[0]即可。
核心原理:当整个原数组遍历结束后,原数组中前k大的元素就会全部被拷贝到tempHeap中来,只要保持tempHeap是一个小根堆数组,那么tempHeap[0]就是这k个元素中最小的那个.,那么其中tempHeap[0]就是第k大的元素了。
java代码示例:
public class FindKthMaxUtility {
public static int find(int[] arr,int k){
if(k>arr.length){
return 0;
}
int[] tempHeap=new int[k];
for(int i=0;i<k;i++){
tempHeap[i]=arr[i];
}
heapInsert((tempHeap));
System.out.println();
for(int i=k;i<arr.length;i++){
if(tempHeap[0]<arr[i]){
tempHeap[0]=arr[i];
heapify(tempHeap);
}
}
for(int i=0;i<tempHeap.length;i++){
System.out.print(tempHeap[i]+", ");
}
return tempHeap[0];
}
static void heapInsert(int[] tempHeap){
for(int heapSize=2;heapSize<=tempHeap.length;heapSize++){
int i=heapSize-1;
while(i>0){
int f=(i-1)>>1;
if(tempHeap[i]<tempHeap[f]){
swap(tempHeap,i,f);
i=f;
}else{
break;
}
}
}
}
static void heapify(int[] tempHeap){
int i=0;
while(2*i+1<tempHeap.length){
int l=2*i+1;
int smaller=l+1<tempHeap.length&&tempHeap[l+1]<tempHeap[l]?l+1:l;
if(tempHeap[i]>tempHeap[smaller]){
swap(tempHeap,i,smaller);
i=smaller;
}else{
return;
}
}
}
static void swap(int[] tempHeap,int a,int b){
int temp=tempHeap[a];
tempHeap[a]=tempHeap[b];
tempHeap[b]=temp;
}
}