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

前端 未结 14 2512
清酒与你
清酒与你 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:24

    I would use this code. It includes an instancesOf function, and it runs through each number.

    public class MathFunctions {
    
    public static int mode(final int[] n) {
        int maxKey = 0;
        int maxCounts = 0;
    
        for (int i : n) {
            if (instancesOf(i, n) > maxCounts) {
                maxCounts = instancesOf(i, n);
                maxKey = i;
            }
        }
    
        return maxKey;
    }
    
    public static int instancesOf(int n, int[] Array) {
        int occurences = 0;
        for (int j : Array) {
            occurences += j == n ? 1 : 0;
        }
        return occurences;
    }
    
    public static void main (String[] args) {
        //TODO Auto-generated method stub
        System.out.println(mode(new int[] {100,200,2,300,300,300,500}));
    }
    }
    

    I noticed that the code Gubatron posted doesn't work on my computer; it gave me an ArrayIndexOutOfBoundsException.

提交回复
热议问题