#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],heap[lchild]);
index=lchil
用堆实现最小的K个数的查找:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
最新推荐文章于 2020-12-03 20:32:54 发布