检查值是否在数组中的最快方法

时间:2014-03-14 09:58:55

标签: java algorithm

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

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

1 个答案:

答案 0 :(得分:6)

您可以轻松创建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) {
    ...
}
相关问题