寻找数组中的第K大元素

一、简述
  使用数据结构堆,实现查找数组中的第K大元素。流程如下:数组内容堆化(因为是查找第K大,所以使用大根堆)、依次取出并删除堆的根节点、将剩余元素堆化、取到第K个即为目标元素。
二、代码实现

#include <iostream>
#include <vector>

using namespace std;

int findKth(vector<int> a, int n, int K) {
        int heapSize = n;
        vector<int> aa(a);
        aa.insert(aa.begin(),0);
        /*for将数组元素初始化为大根堆*/
        for(int root = heapSize / 2; root >= 1; root--){
            int rootElement = aa[root];

            int child = root * 2;
            while(child <= heapSize){
                if((child < heapSize) && (aa[child] < aa[child + 1])){
                    child++;
                }

                if(rootElement >= aa[child]){
                    break;
                }
                else{
                    aa[child / 2] = aa[child];
                    child *= 2;
                }

            }
            aa[child / 2] = rootElement;
        }

        int result = 0;
        for(int i = 0; i < K; i++){
            result = aa[1];  //取出根节点元素
            /*while将剩余元素堆化*/
            int lastElement = aa[heapSize --];
            int curNode = 1, childNode = 2;
            while(childNode <= heapSize){
                if((childNode < heapSize) && (aa[childNode] < aa[childNode + 1])){
                    childNode ++;
                }
                if(lastElement >= aa[childNode]){
                    break;
                }
                else{
                    aa[childNode / 2] = aa[childNode];
                    curNode = childNode;
                    childNode *= 2;
                }
            }
            aa[curNode] = lastElement;
        }
        return result;
}


int main()
{
    vector<int> primes {352, 564,453,2,1,34,5,6,7,8,7,5,67,76,56,45,25,2,2,5,4};
    int result = findKth(primes, (int)primes.size(), 8);

    cout << "result = " << result << endl;

    return 0;
}

三、运行结果

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值