Java - 使用 binarySearch 查找数组中特定元素的出现次数,无需 If

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

我正在尝试查找整数在 int 数组中出现的次数,但没有使用 if 语句。

我知道,通常情况下,可以简单地使用 for 或 foreach 遍历数组,并在每次元素与条件匹配时使用 if 递增计数变量。

但是,由于我做不到,所以我正在考虑对数组进行排序并找到其中每组重复元素的第一个和最后一个索引之间的差异,并尝试利用 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 = ??

但是,我对如何找到最后一次出现的索引感到困惑。 AFAIK,binarySearch 是检索数组中特定键的索引的唯一方法。谁能赐教一下?

最后一次出现的索引是下一个值(即value+1)第一次出现的索引减1。

确保处理下一个值存在和不存在的情况。

但是我怀疑您不打算在这里使用库 API,并且您应该遍历数组以计算另一个数组中 all 值的出现次数,并且然后 return 您要查找的数字的出现值。不需要 if

我不确定这是什么规则。这是作弊吗?

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

这个怎么样?我不认为它使用任何 if 语句。

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