如何确定数组中整数的最大频率?

时间:2016-10-08 18:05:59

标签: java

我被问到一个程序在编码测试考试中编写一个函数来检查数组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;
}
}

1 个答案:

答案 0 :(得分:0)

最简单的方法是流式传输数组并将其转换为频率图,按计数对其进行反向排序,并采用第一个元素:

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