我现在正在学习堆,显然更多的关注点在于堆中的最小元素,但是我想知道如何找到最大元素?对于最小元素,你只需返回根节点即可,但是不确定你将如何处理最大元素?
我现在正在学习堆,显然更多的关注点在于堆中的最小元素,但是我想知道如何找到最大元素?对于最小元素,你只需返回根节点即可,但是不确定你将如何处理最大元素?
1
2 3
4 5 6 7
8 9 10 11 12 13
你只需要检查堆数组长度的一半后面的元素,对于上述例子,从7到13。前面的节点都有子节点,因此它们永远不会是最大值。这意味着只需要检查n/2个元素,因此时间复杂度仍为O(n)。
定义变量max
并将其初始化为0。
HeapNode[] h;
int last;
int max=0;
public int getMax() throws Exception {
if (isEmpty()) {
Exception EmptyHeapException = new EmptyHeapException();
throw EmptyHeapException;
} else {
//findMax(0, 0); //If you want to use Iteration
for(int i=0;i<=last;i++)
max = Math.max(h[i].key, max);//Updated Thanks Raul Guiu
return max;
}
}
在每个节点迭代,直到节点为最后一个。
private void findMax(int i, int level) {
if (i > last) return;
if(max<h[i].key)
max=h[i].key;
findMax(2*i+1, level+1);//left node
findMax(2*i+2, level+1);//right node
}
public boolean isEmpty() {
return (last < 0);
}
你可以从堆中获得最大的价值。