PriorityQueue 小根堆和大根堆的讨论
2017-09-27 23:17
567 查看
堆是一种经过排序的完全二叉树,其中任一非终端节点的数据值均不大于(或不小于)其左孩子和右孩子节点的值。
根结点(亦称为堆顶)的关键字是堆里所有结点关键字中最小者的堆称为小根堆。
根结点(亦称为堆顶)的关键字是堆里所有结点关键字中最大者,称为大根堆。
借助类PriorityQueue 可以实现小根堆和大根堆。
对于PriorityQueue ,观察帮助文档,可以发现,这是jdk1.5以后引入的,
对它的说明如下:An unbounded priority queue based on a priority heap,The elements of the priority queue are ordered according to their natural ordering, or by a
at queue construction time, depending on which constructor is used.
The head of this queue is the least element with respect to the specified ordering.
由此可知,它容量没有界限,且默认排序是自然排序,队头元素是最小元素,故我们可以拿来作为小根堆使用。
(要注意:默认的PriorityQueue并非保证了整个队列都是有序的,只是保证了队头是最小的)
对于大根堆,就要借助于comparator比较器,来实现大根堆。(使用默认的初始容量:11)
[java] view
plain copy
PriorityQueue <Integer> maxHeap = new PriorityQueue<Integer>(11, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o2.compareTo(o1);
}
});
这样就实现了,大根堆的功能。
根结点(亦称为堆顶)的关键字是堆里所有结点关键字中最小者的堆称为小根堆。
根结点(亦称为堆顶)的关键字是堆里所有结点关键字中最大者,称为大根堆。
借助类PriorityQueue 可以实现小根堆和大根堆。
对于PriorityQueue ,观察帮助文档,可以发现,这是jdk1.5以后引入的,
对它的说明如下:An unbounded priority queue based on a priority heap,The elements of the priority queue are ordered according to their natural ordering, or by a
Comparatorprovided
at queue construction time, depending on which constructor is used.
The head of this queue is the least element with respect to the specified ordering.
由此可知,它容量没有界限,且默认排序是自然排序,队头元素是最小元素,故我们可以拿来作为小根堆使用。
(要注意:默认的PriorityQueue并非保证了整个队列都是有序的,只是保证了队头是最小的)
对于大根堆,就要借助于comparator比较器,来实现大根堆。(使用默认的初始容量:11)
[java] view
plain copy
PriorityQueue <Integer> maxHeap = new PriorityQueue<Integer>(11, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o2.compareTo(o1);
}
});
这样就实现了,大根堆的功能。
相关文章推荐
- 超市market(堆维护,小根堆+大根堆)
- 大根堆和小根堆的C语言实现
- 堆排序—大根堆,小根堆
- 大根堆-小根堆-堆排序-C实现
- 最大堆/最小堆【大根堆/小根堆】
- 小根堆,大根堆,堆排序
- CJOJ 2482 【POI2000】促销活动(STL优先队列,大根堆,小根堆)
- 【每日N题】大根堆、小根堆
- 【数据结构】堆结构小根堆,大根堆,插入,删除等操作的实现
- 【2015-2016 ACM-ICPC, NEERC, Northern Subregional Contest G】【脑洞 拓扑排序 大根堆小根堆极限维护】Graph DAG加k边使得最小拓扑序最大
- 大根堆 小根堆 找中位数
- 大根堆 小根堆
- 堆的数据结构能够使得堆顶总是维持最大(对于大根堆)或最小(对于小根堆),给定一个数组,对这个数组进行建堆,则平均复杂度是多少?如果只是用堆的 push 操作,则一个大根堆依次输入 3,7,2,4,1,5,8 后,得到的堆的结构示意图是下述图表中的哪个?
- sort 升序还是降序?priority_queue 大根堆还是小根堆?
- 数据结构 之 堆(完全二叉树、大根堆、小根堆)
- 51nod K 汽油补给 大根堆+小根堆....
- 大根堆,小根堆,堆排序
- 如何删除3448病毒(讨论)。
- 关于技术主管的讨论
- 昨天和同事+好友讨论用户控件与用户自定义控件的问题,今天来就在msdn上看到详细的对比