[英]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.