Frequency of Numbers in a 1D Array

前端 未结 6 564
清酒与你
清酒与你 2021-01-27 03:54

its been 6 hours since I have been writing the code but to no avail, I don\'t no where I am making the mistake but I am making some. Its a frequency output program and output sh

6条回答
  •  感动是毒
    2021-01-27 04:18

    /**
     * The methods counts the frequency of each element in an array.
     * 
     * Approach: The method checks if the element is already present in the Map of frequency.
     * If it is not present, add it to the map with the frequency 1 else put it in the map with 
     * an increment by one of it's existing frequency.
     * 
     * @param arr list of elements
     * @return frequency of each elements
     */
    public static Map countFrequency(int[] arr) {
        Map frequency= new HashMap();
        for(int i = 0; i < arr.length; i++) {
            if(frequency.get(arr[i])==null) {
                frequency.put(arr[i], 1);
            }
            else {
                frequency.put(arr[i],frequency.get(arr[i])+1);
            }
        }
        System.out.println("\nMap: "+frequency);
        return frequency;
    }
    

提交回复
热议问题