find the frequency of elements in a java array

后端 未结 9 1553
灰色年华
灰色年华 2020-12-03 16:40

I have an int array:

{1,2,4,2,3,5,6,4,3}

How can I find frequencies of array elements like 1=1,2=2,3=2,4=4... I need a class w

9条回答
  •  盖世英雄少女心
    2020-12-03 17:16

    If range of the elements of the array is specified and limited to array size, the best solution is using hash map. T(n) = O(n), auxiliary space = O(n).

    public static void findCount3(int[] a){
        Map hm = new HashMap();     
        for(int i = 0; i < a.length; i++){
                if(!hm.containsKey(a[i])){
                   hm.put(a[i], 1);
                }else{
                   hm.put(a[i], hm.get(a[i])+1);
        }               
        System.out.println(hm);         
    }
    

提交回复
热议问题