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

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

    You should be able to do this in N operations, meaning in just one pass, O(n) time.

    Use a map or int[] (if the problem is only for ints) to increment the counters, and also use a variable that keeps the key which has the max count seen. Everytime you increment a counter, ask what the value is and compare it to the key you used last, if the value is bigger update the key.

    public class Mode {
    public static int mode(final int[] n) {
        int maxKey = 0;
        int maxCounts = 0;
    
        int[] counts = new int[n.length];
    
        for (int i=0; i < n.length; i++) {
            counts[n[i]]++;
            if (maxCounts < counts[n[i]]) {
                maxCounts = counts[n[i]];
                maxKey = n[i];
            }
        }
        return maxKey;
    }
    
    public static void main(String[] args) {
        int[] n = new int[] { 3,7,4,1,3,8,9,3,7,1 };
        System.out.println(mode(n));
    }
    }
    

提交回复
热议问题