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. 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. 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:
// 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.
// 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) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With