zoukankan      html  css  js  c++  java
  • 找一个数组里面的众数

    找一个数组里面的众数, 即出现次数多的那个数。

    给出一个数组,找出重复最多的那个元素。

    知识点:Map的遍历

        https://www.cnblogs.com/bors/p/map.html
        
        @Test
        public void testNumerousNum() {
            int array[] = {0, 0, 0, 0, 1, 4, 2, 1, 4, 2, 2, 2, 4, 4, 4, 4};
            String numerousNum = findNumerousNum(array);
    
            System.out.println(numerousNum);
        }
    
        String findNumerousNum(int arr[]) {
            if (arr.length < 1) {
                return null;
            }
            // map的k表示数组元素num,v表示num重复次数
            Map<Integer, Integer> numMap = new HashMap<Integer, Integer>();
            for (int num : arr) {
                if (!numMap.containsKey(num)) {
                    numMap.put(num, 1);
                } else {
                    numMap.put(num, numMap.get(num) + 1);
                }
            }
    
            int maxK = 0;
            int maxV = 0;
            for (Map.Entry<Integer, Integer> entry : numMap.entrySet()) {
                if (entry.getValue() > maxV) {
                    maxK = entry.getKey();
                    maxV = entry.getValue();
                }
            }
            System.out.println(numMap.toString());
            return "众数: " + maxK + "
    重复次数: " + maxV;
        }

    结果:

    {0=4, 1=2, 2=4, 4=6}
    众数: 4
    重复次数: 6
  • 相关阅读:
    vue
    mongodb
    ejs模板引擎
    ajax
    node.js2
    node.js1
    bootstrap,ECMA
    商城
    面试:----Struts和springmvc的区别--区别上
    OpenStack
  • 原文地址:https://www.cnblogs.com/bors/p/numerousNum.html
Copyright © 2011-2022 走看看