C++:heap堆的相关操作
#include<algorithm> //头文件
make_heap() //建堆,最大值在所给范围的最前面,其他位置不确定
pop_heap() //将堆顶(所给范围最前面)元素移到所给范围的最后,并将余下的最大的元素放在最前面
pop_back() //将所给范围的最后一个元素删除
push_back() //在所给范围的末尾加入新的元素
push_heap() //调整元素的位置,重新构建堆,即将最大元素放在第一位
sort_heap() //将堆中元素从小到大排序
可以通过下面这个题目来进行堆操作的相关验证:输入n个整数,找出其中最小的K个数。
使用Vs code进行单步调试,可以观察res的vector的变化过程。
**
解决改题目,提供了如下两种方法:
方式1:使用冒泡法
方式2:使用堆排序
**
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
//冒泡法得出最小的k个不相同的数字
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
int n = input.size();
int temp = 0;
int num = k;
vector<int> res;
if(input.empty())
{
return res;
}
if(input.size() < k)
{
return res;
}
for(int i = 0; i<num; i++)
{
for(int j = n-1; j>i; j--)
{
if(input[j-1] > input[j])
{
temp = input[j];
input[j] = input[j-1];
input[j-1] = temp;
}
}
if(i>1 && input[i] == input[i-1]) //有相同的数字,则算作一种类别
{
num++;
}
}
for(int i = 0; i<num; i++)
{
res.push_back(input[i]);
}
return res;
}
};
class Solution1 {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
int len = input.size();
if(input.empty() || input.size() < k)
{
return vector<int>();
}
vector<int> res(input.begin(), input.begin()+k);
// auto cmp = [](const int x, const int y) { return x < y;};
//建堆 最大值在所给范围的最前面,其他位置不确定
make_heap(res.begin(), res.end());
for(int i = k; i<len; i++)
{
if(input[i] < res[0]) // 当堆顶元素比新元素大,需要删除掉,插入新元素
{
//将当前最大的从堆中删除
pop_heap(res.begin(), res.end()); //将堆顶(所给范围最前面)元素移到所给范围的最后,并将余下的最大的元素放在最前面
res.pop_back(); //将所给范围的最后一个元素删除
//现在容器中加入,再push
res.push_back(input[i]); //在所给范围的末尾加入新的元素
push_heap(res.begin(),res.end()); //调整元素的位置,重新构建堆
}
}
//从小到大输出
sort_heap(res.begin(), res.end()); //将堆中元素从小到大排序
return res;
}
};
int main()
{
Solution1 S;
vector<int> input = {4,5,1,6,2,7,3,8};
vector<int> result;
result = S.GetLeastNumbers_Solution(input, 3);
for(int i = 0; i<result.size(); i++)
{
cout<<result[i]<<endl;
}
system("pause");
return 0;
}