算法12:找一個數組里面的眾數


找一個數組里面的眾數, 即出現次數多的那個數。

 

給出一個數組,找出重復最多的那個元素。

知識點: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 + "\n重復次數: " + maxV;
    }

 

結果:

{0=4, 1=2, 2=4, 4=6}
眾數: 4
重復次數: 6

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM