检查最小-最大堆 java 的奇偶级别
这是我编写的一个方法,用于确定数组的给定索引是否表示堆的最大级别或最小级别,其中最小级别具有偶数深度(包括 0),最大级别具有奇数深度。它工作得很好,但它的运行时间是(我认为)O(log N)。有没有更有效的方法来做到这一点,例如具有恒定运行时间的简单数学计算?请注意,此方法假设数据从数组的索引 1 开始,而不是从索引 0 开始。
private boolean isMaxLevel(int i)
{
int border = 1;
int prev = 1;
int count = 1;
boolean isMax = false;
// alternates boolean between true and false as each level is checked.
while (true)
{
if (i >= prev && i <= border)
return isMax;
isMax = !isMax;
prev = border + 1;
count *= 2;
border += count;
}
}
So this is a method I wrote to determine if a given index of an array represents a max level or a min level of a heap, where min level has even depth (including 0), max level has odd depth. It works fine, but its run time is (I think) O(log N). Is there a more efficient way of doing this like a simple math calculation that has a constant run time? Note that this method assumes the data starts at index 1 of the array, not index 0.
private boolean isMaxLevel(int i)
{
int border = 1;
int prev = 1;
int count = 1;
boolean isMax = false;
// alternates boolean between true and false as each level is checked.
while (true)
{
if (i >= prev && i <= border)
return isMax;
isMax = !isMax;
prev = border + 1;
count *= 2;
border += count;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不清楚你的要求是什么,但这可能对你有帮助。
印刷
Its not clear to me what your requirement is but this might help you.
prints
我不确定这是否更快,它可能取决于实现,但是:
返回正确的值。从数学上考虑一下。您想找出以下关于 i 的 n 项是正确的。如果 n 是奇数,则有最高级别,如果 n 是偶数,则有最低级别。
2ⁿ-1 <= i < 2ⁿ⁺ⁱ-1
求解 n 我们得到:
然后我们可以测试 n 是否为奇数 (n%2 == 1)
I'm not sure if this in any faster, it's probably implementation dependent, but:
Returns the correct value. Think of it mathematically. You want to find out for which n the following is true about i. If n is odd you have a max level, if n is even you have a min level.
2ⁿ-1 <= i < 2ⁿ⁺ⁱ-1
Solving this for n we get:
Then we can just test if n is odd (n%2 == 1)
我们必须检测最小级别和最大级别范围
1 => pow(2,0) --> 最低等级
2-3 => pow(2,1) 到 pow(2,2)-1 --> 最高级别
4-7 => pow(2,2) 到 pow(2,3)-1 --> 最低级别
8-15 => pow(2,3) 到 pow(2,4)-1 --> 最大级别
c 实现
we have to detect the min level and max level ranges
1 => pow(2,0) -->min level
2-3 => pow(2,1) to pow(2,2)-1 -->max level
4-7 => pow(2,2) to pow(2,3)-1 -->min level
8-15 => pow(2,3) to pow(2,4)-1 -->max level
c implementation