堆一般分为最大堆
和最小堆
,可以想象成二叉树形式,但一般用数组存储。
来看下最大堆的常用操作:
int threshold = 3;
var maxHeap = new PriorityQueue<Integer>(Collections.reverseOrder());
maxHeap.offer(2);
maxHeap.offer(6);
maxHeap.offer(4);
maxHeap.offer(1);
if (maxHeap.size() > threshold) maxHeap.poll();
maxHeap.offer(3);
if (maxHeap.size() > threshold) maxHeap.poll();
while (!maxHeap.isEmpty()){
System.out.print(maxHeap.poll() + " ");
}
// 3 2 1
实战
一位喜欢提问、尝试的程序员
(转载本站文章请注明作者和出处 姚屹晨-yaoyichen)