[英]get kth-largest-element-in-an-array - implemented using maxheap but getting time exceeded in leetcode
[英]Using recursion to identify an array as a MaxHeap
在Priority Queue的此实现中,我必须使用递归来确定作为方法IsMaxHeap
的参数接收的数组是否是最大堆。
我想确定我会评估所有可能使该工作成功或无法正常工作的情况。
static boolean isMaxHeap(int[] H, int idx) {
if(2*idx == (H.length -1) && H[2 * idx] <= H[idx])
return true;
if(2*idx > (H.length -1))
return true;
if ((2*idx+1) == (H.length -1) && H[2 * idx] <= H[idx] && H[2 * idx + 1] <= H[idx])
return true;
if((2*idx+1) > (H.length -1))
return true;
if (H[2 * idx] <= H[idx] && H[2 * idx + 1] <= H[idx])
return isMaxHeap(H, (idx + 1));
else
return false;
}
你可以帮帮我吗?
您的代码很难遵循,因为您在条件中进行了许多计算。 因此很难说它是否真的有效。 另外,您编写的基本上是for
循环的递归实现。 也就是说,您检查节点1、2、3、4、5等。
尽管这行得通,但最终您会使用O(n)堆栈空间。 如果堆非常大(例如,数十万个项目),则存在栈溢出的风险。
递归实现此方法的更常见方法是对树进行深度优先遍历。 就是说,您一直沿左孩子走到根,然后上升到一个级别并检查该节点的右孩子,并检查它的左孩子一直到根,依此类推。因此,给定此堆:
1
2 3
4 5 6 7
8 9 10 11 12 13 14 15
您将按以下顺序检查节点:[1、2、4、8、9、5、10、11、3、6、12、13、7、14、15]
这样做可以简化代码,并将堆栈深度限制为O(log n),这意味着即使具有一百万个节点,堆栈深度也不会超过20。
由于您使用2*idx
和2*idx+1
来查找子代,因此我假设已设置数组,以便您的根节点位于索引1。如果根位于索引0,则进行这些计算将是: 2*idx+1
和2*idx+2
。
static boolean isMaxHeap(int[] H, int idx)
{
// Check for going off the end of the array
if (idx >= H.length)
{
return true;
}
// Check the left child.
int leftChild = 2*idx;
if (leftChild < H.length)
{
if (H[leftChild] > H[idx])
return false;
if (!isMaxHeap(H, leftChild)
return false;
}
// Check the right child.
int rightChild = 2*idx + 1;
if (rightChild < H.length)
{
if (H[rightChild] > H[idx])
return false;
return isMaxHeap(H, rightChild);
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.