简体   繁体   English

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

[英]Fastest way to check if value is in array many times

I have an array of some values between -15 and 31 and I have to check, if some x is in this array for ~300 000 000 times. 我有一些介于-1531之间的值的数组,我必须检查,如果某个x在这个数组中~300 000 000次。 Because there is negative values, I can't create boolean array. 因为有负值,我无法创建布尔数组。 Now I am creating HashSet from original array and use .contains() method, but this is too slow. 现在我从原始数组创建HashSet并使用.contains()方法,但这太慢了。 Is there any faster way or trick? 有没有更快的方法或技巧?

Update I create this array from another one (so I can use any structure I want) 更新我从另一个创建这个数组(所以我可以使用我想要的任何结构)

You could easily create a boolean array and just offset the index: 您可以轻松创建一个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;
}

Then to check for presence: 然后检查是否存在:

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

Alternatively, as you're using fewer than 64 bits you could store the whole thing in a single long , and use bitshifting. 或者,当您使用少于64位时,您可以将整个事物存储在一个long整数中,并使用位移。

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

Then to check for presence: 然后检查是否存在:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM