Finding Multiple Modes In An Array

前端 未结 4 1041
醉梦人生
醉梦人生 2021-01-22 10:38

I\'m trying to write a java method which finds all the modes in an array. I know there is a simple method to find the mode in an array but when there are more than one single mo

4条回答
  •  暖寄归人
    2021-01-22 11:18

    Even though this probably isn't the most efficient solution, it will print all the highest modes:

    public static int mode(int a[]) {
        int maxValue=-1, maxCount=0;
        for (int i = 0; i < a.length; i++) {
            int count = 0;
            for (int j = 0; j < a.length; j++) {
                if (a[j] == a[i])
                    count++;
                }
            }
            if (count > maxCount) {
                maxCount = count;
                maxValue = a[i];
            }
        }
    
        //loop again and print only the highest modes
        for (int i = 0; i < a.length; i++) {
            int count = 0;
            for (int j = 0; j < a.length; j++) {
                if (a[j] == a[i])
                    count++;
                }
            }
            if (count == maxCount) {
                System.out.println(a[i]);
            }
        }
    }
    

提交回复
热议问题