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

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

    import java.util.HashMap;

    public class SmallestHighestRepeatedNumber { static int arr[] = { 9, 4, 5, 9, 2, 9, 1, 2, 8, 1, 1, 7, 7 };

    public static void main(String[] args) {
        int mode = mode(arr);
        System.out.println(mode);
    }
    
    public static int mode(int[] array) {
        HashMap hm = new HashMap();
        int max = 1;
        int temp = 0;
    
        for (int i = 0; i < array.length; i++) {
    
            if (hm.get(array[i]) != null) {
    
                int count = hm.get(array[i]);
                count++;
                hm.put(array[i], count);
    
                if (count > max || temp > array[i] && count == max) {
                    temp = array[i];
                    max = count;
                }
            } else
                hm.put(array[i], 1);
        }
        return temp;
    }
    

    }

提交回复
热议问题