算法 - 计算数组中每个数字出现的次数(java)

public class Count { 
    public static void main(String[] args) { 
        Count count = new Count();
        int[] arr = { 10, -2, 33, 140, 25, 26, 10, -2, 0, 25, 10, 33, -2, 50};
        count.printElementsCount(arr);
        // output is (0出现1次,-2出现2次,以此类推):
        //{0=1, -2=3, 33=2, 50=1, 25=2, 10=3, 26=1, 140=1}
    }

    public void printElementsCount(int[] arr) { 
        // use map: key is element,value is count
        Map<Integer, Integer> map = new HashMap<>(10);
        for (int i = 0; i < arr.length; i++) { 
            if (map.containsKey(arr[i])) { 
                Integer count = map.get(arr[i]) + 1;
                map.put(arr[i], count);
            } else { 
                map.put(arr[i], 1);
            }
        }
        System.out.println(map.toString());
    }

}

    原文作者:se-tester
    原文地址: https://blog.csdn.net/dzh0622/article/details/112408607
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞