
#include <iostream>
using namespace std;
class A
{
public:
A(int *data, int len){}
};
template<class T> class MaxHeap{
private:
T *datas;
int MaxSize;
int currentSize;
void KeepHeap(int root);
bool del;
public:
MaxHeap(int MaxSize);
MaxHeap(T *datas, int length);
~MaxHeap();
bool Insert(T data);
T GetMax();
void RemoveMax();
void PrintHeap(){
for (int i=1; i<=currentSize; i++)
{
cout << datas[i] << " ";
}
cout << endl;
}
int GetCurrentSize()
{
return currentSize;
}
//void BuildMaxHeap(T *datas);
};
template <class T> MaxHeap<T>::MaxHeap(T *datas, int length)
{
this->datas = datas;
currentSize = length;
MaxSize = currentSize;
for (int i=currentSize/2; i>0; i--)
{
KeepHeap(i);
}
del = false;
}
template<class T> MaxHeap<T>::MaxHeap(int MaxSize)
{
this->MaxSize = MaxSize;
datas = new T[this->MaxSize+1];
this->currentSize = 0;
del = true;
}
template<class T> MaxHeap<T>::~MaxHeap()
{
if(del)
delete []datas;
}
template<class T> bool MaxHeap<T>::Insert(T data)
{
if (currentSize+1 > MaxSize)
{
return false;
}
datas[++currentSize] = data;
int index = currentSize;
int temp = (index)/2;
while (temp>=1)
{
if (datas[temp]<data)
{
datas[index] = datas[temp];
index = temp;
temp = temp/2;
}else{
break;
}
}
datas[index] = data;
return true;
}
template<class T> T MaxHeap<T>::GetMax()
{
return datas[1];
}
template<class T> void MaxHeap<T>::KeepHeap(int root)
{
int temp = datas[root];
while (root*2<=currentSize)
{
int child = root*2;
if (child+1<=currentSize && datas[child] < datas[child+1])
{
child++;
}
if (temp > datas[child])
{
break;
}else
{
datas[root] = datas[child];
}
root = child;
}
datas[root] = temp;
}
template<class T> void MaxHeap<T>::RemoveMax()
{
int temp = datas[1];
datas[1] = datas[currentSize];
datas[currentSize] = temp;
currentSize--;
KeepHeap(1);
}
void MinK(int *data, int length, int k)
{
MaxHeap<int> heap(length);
for (int i=1; i<length; i++)
{
if (k>heap.GetCurrentSize())
{
heap.Insert(data[i]);
}else{
if (data[i]<heap.GetMax())
{
heap.RemoveMax();
heap.Insert(data[i]);
}
}
}
heap.PrintHeap();
}
int main(int argc, char* argv[])
{
// MaxHeap<int> h(4);
// h.Insert(1);
// h.Insert(2);
// h.Insert(3);
int data[] = {-1,15,24,3,8,7,6,5,7};
int len = sizeof(data)/sizeof(int);
MaxHeap<int> h(data, len-1);
for (int i=1; i<len; i++)
{
h.RemoveMax();
}
for (i=1; i<len; i++)
cout << data[i] << " ";
cout << endl;
MinK(data,len,3);
return 0;
}

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?