简体   繁体   中英

Java - Use binarySearch to find # of occurrences of certain element in array, without If

I'm trying to find the number of occurrences of an integer in an int array, but without using if statements.

I understand that, normally, one could simply iterate through the array using for or foreach, and increment a count variable each time an element matches the criteria using if.

Since I am unable to, however, I'm considering sorting the array and find the difference between the first and last indices of each set of repeating elements in it, and trying to utilize binarySearch to get the indices, like so:

int[] list = {9, 9, 7, 5, 9, 9, 3, 1, 1};
Arrays.sort(list);

// list is now {1, 1, 3, 5, 7, 9, 9, 9, 9} for binarySearch

/* Finding the difference between the indices of the first and last occurrences of
   9, for example, could yield the number of occurrences. */

int firstIndex = Arrays.binarySearch(list, 0);
// int lastIndex = ??

However, I'm confused as to how I could find the index of the last occurrence. AFAIK, binarySearch is the only way to retrieve the index of a specific key in an array. Could anyone enlighten me?

How about this? I don't think it uses any if statements.

long count = Arrays.stream(list).filter(x -> x == number).count();

The index of the last occurrence is the index of the first occurrence of the next value (ie value+1 ) minus 1.

Make sure to handle both the cases where the next value exists and where it doesn't.

However I suspect that you're not meant to use library APIs here, and that you should iterate through the array counting the occurrences of all values, in another array, and then return the occurrences value for the number you're looking for. No if s required.

I'm not sure what the rules of this are. Is this cheating?

static int count(int number, int[] list) {
    int count = 0;
    for (int a : list)
        switch(a == number ? 1 : 0) {
            case 1: count++; 
        }
    return count;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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