Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to find if int array contains a number

This is an odd question. I have an integer array in Java, where each int represents a color. They will either be 0xFFFFFFFF or 0x0. What would be the FASTEST way to find if this array contains ANY values equal to 0xFFFFFFFF?

This is my current code:

int length = w * h;
for (int i = 0; i < length; i++) {
    if (pixels[i] == 0xFFFFFFFF) {
        return true;
    }
}

I have no clue if there is a faster way to do this or not. I imagine you vets could have a trick or two though.

EDIT: Seeing as it is just a dumb array of pixels from Bitmap.getPixels(), there's no way it would be sorted or transformed to another storage structure. Thanks for the input, everyone, it seems like looping through is the best way in this case.

like image 540
Kyle Emmerich Avatar asked Aug 22 '11 18:08

Kyle Emmerich


People also ask

How do you check if an array contains a number?

The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.

How do you check if an array contains an integer?

We can use the contains() method to find the specified value in the given array. This method returns a boolean value either true or false . It takes two arguments; the first is an array, and the second is the value to find. The contains() method belongs to ArrayUtils class of Apache commons library.

How do you check if an array has all the same values Java?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.


1 Answers

No, there is no faster way unless the array of integers is already sorted, which I doubt given it's an array of colours.

To scan through an unsorted array takes linear time "O(n)". That's what you do, and you exit the method as soon as a match is found which is good too.

like image 144
Paul Avatar answered Sep 24 '22 19:09

Paul