gpt4 book ai didi

java - 多次检查值是否在数组中的最快方法

转载 作者:搜寻专家 更新时间:2023-11-01 02:09:05 25 4
gpt4 key购买 nike

我有一个介于 -1531 之间的一些值的数组,我必须检查这个数组中是否有一些 x ~300 000 000 次。因为有负值,所以我无法创建 boolean 数组。现在我正在从原始数组创建 HashSet 并使用 .contains() 方法,但这太慢了。有没有更快的方法或技巧?

更新 我从另一个数组创建这个数组(所以我可以使用我想要的任何结构)

最佳答案

您可以轻松地创建一个boolean 数组并仅偏移索引:

// Do this once...
int minValueInclusive = -15;
int maxValueExclusive = 31;
boolean[] presence = new boolean[maxValueExclusive - minValueInclusive + 1];
for (int value : array) {
presence[value - minValueInclusive] = true;
}

然后检查是否存在:

if (presence[index - minValueInclusive]) {
...
}

或者,当您使用少于 64 位时,您可以将整个内容存储在单个 long 中,并使用位移位。

// Do this once...
int minValueInclusive = -15;
long presence = 0;
for (int value : array) {
presence |= 1L << (value - minValueInclusive);
}

然后检查是否存在:

if ((presence & (1L << (index - minValueInclusive))) != 0) {
...
}

关于java - 多次检查值是否在数组中的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22401648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com