求数组中第k大的元素

实现逻辑:创建一个长度为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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值