Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to check if value is in array many times

Tags:

java

algorithm

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)

like image 684
JohnDow Avatar asked Mar 20 '23 05:03

JohnDow


1 Answers

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) {
    ...
}
like image 67
Jon Skeet Avatar answered Mar 22 '23 19:03

Jon Skeet