簡體   English   中英

Java-使用binarySearch查找數組中某些元素的出現次數,沒有If

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

我正在嘗試查找int數組中整數出現的次數,但沒有使用if語句。

我了解,通常情況下,可以使用for或foreach簡單地遍歷數組,並在每次元素匹配條件時使用if遞增一個count變量。

但是,由於無法執行此操作,因此我正在考慮對數組進行排序,並找到其中每個重復元素集的第一個索引與最后一個索引之間的差異,並嘗試利用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是檢索數組中特定鍵的索引的唯一方法。 誰能啟發我?

這個怎么樣? 我認為它不使用任何if語句。

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

最后一次出現的索引是下一個值(即value+1 )減去1的第一次出現的索引。

確保處理下一個值存在和不存在的情況。

但是,我懷疑您不是要在這里使用庫API,而是應該遍歷該數組,對另一個數組中所有值的出現進行計數,然后返回要查找的數字的出現值。 否, 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM