作业: 要求输入$i$个数字时候计算这$i$个数字的中位数。

堆的实现利用了c++的make_heap(),sort_heap函数,类似优先队列。

1. 最小堆的实现代码:

/**************最小堆**********/
class MinHeap
{
public:
    void createHeap()
    {
        make_heap(heap.begin(), heap.end()); //堆化
        sort_heap(heap.begin(), heap.end());//排序
    }
/**************每次插入一个元素后需要对整体进行排序,维持优先序列特性*****************/
    void push(int i)
    {
        heap.push_back(i);//插入
        createHeap();//排序,最小值为第一个元素
    }
    int top()
    {
        return heap[0];//返回最小值
    }
/***************返回最最小值中的最后一个元素**************/
    int back()
    {
        int a = heap[heap.size()-1];
//        heap.pop_back();
        return a;
    }
    int size()
    {
        return heap.size();
    }
    void print()
    {
        for(auto i : heap)
        {
            cout << i << " ";
        }
        cout << endl;
    }
/**************删除最后的一个元素,即最小堆中最大元素************/
    void pop()
    {
        heap.pop_back();
    }
public:
    vector<int> heap;
};
View Code

相关文章:

  • 2022-12-23
  • 2021-06-09
  • 2022-12-23
  • 2021-10-13
  • 2021-08-27
  • 2022-12-23
  • 2021-06-27
  • 2021-09-10
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-14
  • 2021-08-12
相关资源
相似解决方案