簡體   English   中英

如何確定數組中整數的最大頻率?

[英]How to ge the maximum frequency of the Integers in Array?

我被問到一個程序在編碼測試考試中編寫一個函數來檢查數組A中整數的最大頻率以返回值:例如:

A[0]: 10
A[1]: 7
A[2]: 10
A[3]: 10 

將產量輸出為10

class Solution {
    public int solution(int[] A) {
        // write your code in Java SE 8
  int count = 1, tempCount;
  int mostOften = A[0];
  int temp = 0;
  for (int iCounter = 0; iCounter < (A.length - 1); iCounter++)
  {
    temp = A[iCounter];
    tempCount = 0;
    for (int jCounter = 1; jCounter < A.length; jCounter++)
    {
      if (temp == A[jCounter])
        tempCount++;
    }
    if (tempCount > count)
    {
      mostOften = temp;
      count = tempCount;
    }
  }
  return mostOften;
}
}

最簡單的方法是流式傳輸數組並將其轉換為頻率映射,按計數反向排序,並獲取第一個元素:

public int solution(int[] a) {
    return Arrays.stream(a)
                 .boxed()
                 .collect(Collectors.groupingBy
                              (Function.identity(), Collectors.counting()))
                 .entrySet()
                 .stream()
                 .sorted(Map.Entry.<Integer, Long> comparingByValue().reversed())
                 .findFirst()
                 .map(Map.Entry::getKey)
                 .get();
}

暫無
暫無

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

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