简体   繁体   English

Java-使用binarySearch查找数组中某些元素的出现次数,没有If

[英]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. 我正在尝试查找int数组中整数出现的次数,但没有使用if语句。

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. 我了解,通常情况下,可以使用for或foreach简单地遍历数组,并在每次元素匹配条件时使用if递增一个count变量。

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: 但是,由于无法执行此操作,因此我正在考虑对数组进行排序,并找到其中每个重复元素集的第一个索引与最后一个索引之间的差异,并尝试利用binarySearch来获取索引,如下所示:

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. AFAIK,binarySearch是检索数组中特定键的索引的唯一方法。 Could anyone enlighten me? 谁能启发我?

How about this? 这个怎么样? I don't think it uses any if statements. 我认为它不使用任何if语句。

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. 最后一次出现的索引是下一个值(即value+1 )减去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. 但是,我怀疑您不是要在这里使用库API,而是应该遍历该数组,对另一个数组中所有值的出现进行计数,然后返回要查找的数字的出现值。 No if s required. 否, if需要。

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;
}

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

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