#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
用堆实现最小的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通过智能技术生成