找一個數組里面的眾數, 即出現次數多的那個數。
給出一個數組,找出重復最多的那個元素。
知識點: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