用堆实现最小的K个数的查找:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

这篇博客介绍了一种用堆来寻找一组整数中最小K个数的方法。通过创建一个大顶堆并不断调整,可以在O(n log k)的时间复杂度内找到最小的K个数。示例代码展示了一个C++解决方案,用于处理给定的整数数组并输出最小的4个数。
摘要由CSDN通过智能技术生成
#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    vector<int> heap;
    void insert(int val){
        heap.push_back(val);
        int index=heap.size()-1;
        int father=(index-1)/2;
        while(index>0){
            if(heap[index]>heap[father]){
                swap(heap[index],heap[father]);
                index=father;
                father=(index-1)/2;
            }
            else
                break;
        }
    }

    void pop(int k,int val){
        heap[0]=val;
        int max_index=k-1;
        int index=0;
        int lchild;
        int rchild;
        while(index<max_index){
            lchild=index*2+1;
            rchild=index*2+2;
            if(lchild>max_index)
                break;
            else if(rchild>max_index){
                if(heap[index]<heap[lchild]){
                    swap(heap[index],he
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值