Java 如何计算数组中整数的最大频率?

Java 如何计算数组中整数的最大频率?,java,Java,我被要求在Codibility test test中编写一个程序,以编写一个函数来检查数组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 =

我被要求在Codibility test test中编写一个程序,以编写一个函数来检查数组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;
}
}
类解决方案{
公共int解决方案(int[]A){
//用JavaSE8编写代码
int count=1,tempCount;
int mostOften=A[0];
内部温度=0;
对于(int-iCounter=0;iCounter<(A.length-1);iCounter++)
{
温度=A[i计数器];
tempCount=0;
for(int jCounter=1;jCounter计数)
{
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();
}
public int解决方案(int[]a){
返回数组.stream(a)
.boxed()
.collect(收集器.groupingBy
(Function.identity(),collector.counting())
.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue().reversed())
.findFirst()
.map(map.Entry::getKey)
.get();
}

最简单的方法是对数组进行流式处理并将其转换为频率图,按计数对其进行反向排序,然后获取第一个元素:

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();
}
public int解决方案(int[]a){
返回数组.stream(a)
.boxed()
.collect(收集器.groupingBy
(Function.identity(),collector.counting())
.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue().reversed())
.findFirst()
.map(map.Entry::getKey)
.get();
}

您应该只需要通过阵列一次。你有一个嵌套循环,所以你需要去掉它。另外,通过“使用JavaSE8”,我想他们是在告诉你使用流。使用
Arrays.stream()
从数组中创建流。您应该只需要通过数组一次。你有一个嵌套循环,所以你需要去掉它。另外,通过“使用JavaSE8”,我想他们是在告诉你使用流。使用
Arrays.stream()
从数组中创建流。