Finding all numbers in a array with top frequency?

Viewed 2732

I am trying to find out all the numbers with maximum frequency. i.e If maximum frequency is 5 then, I need all numbers that occurred 5 times in a array.

let us consider following example of array:

1 8 7 8 9 2 1 9 6 4 3 5

Here, Most frequent numbers are 8, 1, 9 with highest frequency of 2. My expected output is something like this:

8 => 2
1 => 2
9 => 2

In my project, I am trying to find out most frequent numbers and least frequent numbers. Here I want just most frequent numbers.

I have generated 1000 random numbers similar to my project scenario and have calculated distinct numbers and then their occurrence.

    int n=100;
    int N=1000;

    int data[] = new int[N];
    Set<Integer> set = new HashSet<Integer>();

    Random random = new Random();

    for(int i=0;i<N;i++){
        int  number = random.nextInt(n);
        data[i] = number;
        set.add(number);
    }

    int frequency[] = new int[set.size()];
    Integer[] distinct = set.toArray(new Integer[set.size()]);

    for (int j=0;j<set.size();j++){
        int count=0;
        for(int k=0;k<N;k++){
            if(distinct[j]==data[k]){
                count = count+1;
            }
        }
        frequency[j] = count;
    }

After calculating frequencies of each number, I have calculated numbers with most frequencies using answer from here which is optimized one.

    int max = Integer.MIN_VALUE;
    List<Integer> vals = new ArrayList<>();

    for (int q=0; q < frequency.length; ++q) {

        if (frequency[q] == max) {
            vals.add(q);
        }

        else if (frequency[q] > max) {
            vals.clear();
            vals.add(q);
            max = frequency[q];
        }
    }

    for(int num : vals){
        System.out.println(distinct[num]+" => "+frequency[num]);
    }

Here, Loop in first code making whole process slower. This is only part of large code and sample test case.

I want to make the process faster since there may be large elements in the array in real case.

Anyone have way to optimize those loops ? or some other way to get the result ?

Any kind of help is appreciated.

5 Answers
Related