简体   繁体   中英

How to ge the maximum frequency of the Integers in Array?

I was asked a program to write in codility test exam to write a function that check the maximum frequency of a integers in array A in return the value : for example:

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

Will produce output as 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;
}
}

The easiest approach would be to stream the array and convert it to a frequency map, reverse sort it by the count, and take the first element:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM