Write a mode method in Java to find the most frequently occurring element in an array

前端 未结 14 2531
清酒与你
清酒与你 2020-11-29 07:17

The question goes:

Write a method called mode that returns the most frequently occurring element of an array of integers. Assume that the array has at le

14条回答
  •  盖世英雄少女心
    2020-11-29 07:40

    Here is my answer.

    public static int mode(int[] arr) {
        int max = 0;
        int maxFreq = 0;
    
        Arrays.sort(arr);
        max = arr[arr.length-1];
    
        int[] count = new int[max + 1];
    
        for (int i = 0; i < arr.length; i++) {
            count[arr[i]]++;
        }
    
         for (int i = 0; i < count.length; i++) {
            if (count[i] > maxFreq) {
                maxFreq = count[i];
            }
        }
    
        for (int i = 0; i < count.length; i++) {
            if (count[i] == maxFreq) {
                return i;
            }
        }
        return -1;
    }
    

提交回复
热议问题