offer(E e) | 插入元素 | O(log n) |
poll() | 移除并返回堆顶元素(队列为空时返回null ) | O(log n) |
peek() | 查看堆顶元素(不删除,队列为空时返回null ) | O(1) |
size() | 返回队列元素个数 | O(1) |
PriorityQueue 实现大小堆
通过 Comparator 比较器控制堆序方向:
1. 最小堆(默认行为)
- 自然顺序:元素必须实现
Comparable
接口 -
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
2. 最大堆(自定义比较器)
- 使用反向比较器:
-
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a)