ocurre con mayor frecuencia (int [] a) - java

im trying to find the number that occurs the most in a given array of int. here is my code, it works but there are some inconsistencies. also, if u can let me know how i can make it better, i think my code is too long!!

public static int countOccurrences(int[] a, int x) {
    int count = 0;
    for(int i=0;i<a.length;i++) {
        if(a[i] == x) count++;
    return count;

public static int occursMostOften(int[] a) {
    int[] count = new int[a.length];
    boolean[] duplicate = new boolean[a.length];
    for(int i = 0; i < a.length;i++) {
        if(duplicate[i] != true) {
            count[i] = countOccurrences(a,a[i]);
            duplicate[i] = true;
    return a[maxIndex(count)];
private static int maxIndex(int[] a) {
    int max = 0;
    for(int i = 1; i<a.length;i++) {
        if(a[i-1]<a[i]) max = i;
    return max;     

preguntado el 31 de julio de 12 a las 10:07

2 Respuestas

If this is an assignment (which I assume it is), your code meets the requirements, though not the most optimal.

If you have learned about a data structure called a Map, use that instead. The clave in the map will be the value in the array, and the propuesta de in the map the count of times you have seen this value.

This will reduce the complexity of your code. Sequence of operations are:

For each value in the array

  1. If the value exits in the map, update the count
  2. If not, create a new entry with a count of one

At the end, you can iterate through the map to find the most occuring value.

Respondido 31 Jul 12, 11:07

No, I can think of an O(n log n) algorithm, but that's best left as an exercise. - Luis Wassermann

Your code perform linear scan of full array for each non duplicate number. With array of size n que tiene n distinct values complexity of your code will be O(n^2).

You can do it better in O(n) with following algorithm:

  • Iterate through all numbers in array
  • For each number add it to the map (Map<Integer, Integer>) that holds number and it count
  • If number exist in the map get current count, increment, and put back to the map
  • If number not exists just oput that entry with count 1 to the map
  • After all iterations complete, retrieve values and fins maximum.

Respondido 31 Jul 12, 11:07

I'm not sure, but seems we can achieve results on plain arrays faster. Need to think. - contratiempo

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.