- 堆:一种二叉树的结构–完全二叉树,且每个节点的值都≥或≤孩子节点。
- 最大堆:每个节点的值都≥孩子节点(堆顶元素是最大值)
- 最小堆:每个节点的值都≤孩子节点(堆顶元素是最小值)
- 复杂度
- 访问(acess):无
- 搜索:O(1) (堆顶)
- 添加:O(logN)
- 删除:O(logN) 一般是堆顶
- Python常用操作
import heapq
//创建堆
minheap = []
//添加元素
heapq.heappush(minheap,10)
heapq.heappush(minheap,8)
heapq.heappush(minheap,6)
heapq.heappush(minheap,2)
heapq.heappush(minheap,11)
//查看堆顶元素
print(minheap[0])
//删除堆顶元素
heapq.heappop(minheap)
//长度
len(minheap)
# empty?
len(s)==0
//遍历
while len(minheap)!=0:
print(heap.heappop(minheap))
//最大堆则将元素乘以-1再进行操作
- java常用操作
//创建最小堆
PriorityQueue<Integer> minheap = new PriorityQueue<>();
//创建最大堆
PriorityQueue<Integer> maxheap = new PriorityQueue<>(Collections.reverseOrder());
//添加元素
minheap.add(10);
minheap.add(8);
minheap.add(9);
minheap.add(11);
minheap.add(2);
maxheap.add(10);
maxheap.add(8);
maxheap.add(9);
maxheap.add(11);
maxheap.add(2);
System.out.println(minheap.toString()); //[2,8,9,11,10]
System.out.println(maxheap.toString()); //[11,10,9,8,2]
//查找堆顶元素
minheap.peek();
maxheap.peek();
//删除
minheap.poll();
maxheap.poll();
//长度
minheap.size();
maxheap.size();
//遍历
while(!minheap.isEmpty()){
System.out.println(minheap.poll());
}