最大堆(最小堆)C++实现源码
来源:互联网 发布:21天学通java第7版好吗 编辑:程序博客网 时间:2024/06/03 19:39
写在前面
最近渐渐爱上写博客,觉得每天学到的知识需要保鲜,写的源码也能及时与大家分享,接下来进入正题。
最大堆(最小堆)
最大堆(最小堆)是非常重要的数据结构,公司面试时经常会被问到,在这里,我不会详细介绍它的原理,而是介绍它的适用场景以及两种写法,对原理不了解的可以查看:
https://en.wikipedia.org/wiki/Heap_%28data_structure%29
假设有10万个数,让你求最小的k个数,你会怎么做?
- 先排序,然后取前k个数,时间复杂度O(nlogn)
- 维护k个数的最大堆,时间复杂度O(nlogk)
考虑第一种方式,当内存有限时,没法一次载入10万个数,排序不可取,而第二种方式,每次只载入一个数,最多存储k个数(最大堆),当堆满时,通过比较当前数与堆顶值,若堆顶值大,则删除堆顶,插入当前数,反之,则不做任何操作,也就是说,最大堆一直存储着当前载入数里最小的k个数。
最大堆C++实现源码
这里给出了两种写法,最小堆同理,值得注意的是,最大堆(最小堆)一定是一颗完全二叉树,可以用数组表示,如有错误还望指正。
- 非递归写法
#include <vector>#include <cassert>using namespace std;class MaxHeap{private: vector<int> heap; int size;public: void make_heap(vector<int>& nums, int s) { //构建堆 heap.assign(nums.begin(), nums.end()); size = s; for (int i = size / 2 - 1; i >= 0; i--) down(i); } void push(int num) { //插入元素 heap.push_back(num); size++; up(size - 1); } int pop() { //删除元素 assert(size > 0); int result = heap[0]; heap[0] = heap[size - 1]; heap.pop_back(); size--; down(0); return result; } void down(int index) { assert(index >= 0); int temp = heap[index]; index = index * 2 + 1; while (index < size) { if (index + 1 < size && heap[index] < heap[index + 1]) index++; if (heap[index] < temp) break; else { heap[(index - 1) / 2] = heap[index]; index = index * 2 + 1; } } heap[(index - 1) / 2] = temp; } void up(int index) { assert(index < size); int temp = heap[index]; while (index > 0 && temp > heap[(index - 1) / 2]) { heap[index] = heap[(index - 1) / 2]; index = (index - 1) / 2; } heap[index] = temp; }};
- 递归写法
void down(int index){ assert(index >= 0); int temp = index; index = index * 2 + 1; if (index >= size) return; if (index + 1 < size && heap[index] < heap[index + 1]) index++; if (heap[index] < heap[temp]) return; else { swap(heap[index], heap[temp]); down(index); }}void up(int index){ assert(index < size); if (index == 0) return; if (heap[index] < heap[(index - 1) / 2]) return; else { swap(heap[index], heap[(index - 1) / 2]); up((index - 1) / 2); }}
很明显,递归写法两元素交换次数比非递归写法多。
0 0
- 最大堆(最小堆)C++实现源码
- 最小堆&&最大堆的实现(c++)
- 最小堆&&最大堆的实现(c++)
- 最小堆&&最大堆的实现(c++)
- STL源码—heap最大堆,最小堆(TT)
- 堆,最大堆,最小堆,最大左高树 源码
- 最小堆与最大堆的实现
- 最大堆与最小堆的实现
- 最大堆、最小堆C++实现
- 最大堆/最小堆
- 最小堆。最大堆。
- 最大堆/最小堆
- 最大堆/最小堆
- 最大堆/最小堆
- 最大堆、最小堆
- 最大堆/最小堆
- 最大堆/最小堆
- 最大堆/最小堆
- 666深度讲解函数调用过程
- 决策树——ID3构建决策树
- C#学习笔记 4 常量和变量
- 欢迎使用CSDN-markdown编辑器
- JSX语法详解
- 最大堆(最小堆)C++实现源码
- 【23种设计模式】之 迭代器模式(Iterator Pattern)
- MYSQL API 的MYSQL结构体(MYSQL连接莫名其妙为空)的初始化问题
- 抽帧程序
- CSS继承特性
- Java位运算
- RecyclerView.Adapter notifyDataSetChanged 不起作用
- Java实现AES加密
- mac 开启Eclipse代码提示功能