1. 程式人生 > >數組中出現最多的數,以及接口 Map.Entry<K,V>

數組中出現最多的數,以及接口 Map.Entry<K,V>

int try tools pub length rem value contains span

 1 package test.tools;
 2 
 3 import java.util.Collection;
 4 import java.util.Collections;
 5 import java.util.HashMap;
 6 import java.util.Map;
 7 
 8 public class TestArr {
 9     
10     public static void MaxCount(int[] arr) {
11         Map<Integer, Integer> map = new HashMap<Integer,Integer>();
12 for(int i=0; i<arr.length; i++) { 13 //數組中已經出現此數字,次數加1 14 if(map.containsKey(arr[i])){ 15 int count = map.get(arr[i]); 16 /*HashMap不允許key重復*/ 17 //map.remove(arr[i]); 18 map.put(arr[i], count+1); 19 }else
{ 20 //數字首次出現,次數設置為1 21 map.put(arr[i], 1); 22 } 23 } 24 System.err.println(map); 25 Collection<Integer> collection = map.values(); 26 // 找出map的value中最大值 27 int maxCount = Collections.max(collection); 28 int
num = 0; 29 for(Map.Entry<Integer, Integer> entry : map.entrySet()){ 30 //得到value為maxCount的key,也就是數組中出現次數最多的數字 31 if(entry.getValue() == maxCount){ 32 num = entry.getKey(); 33 } 34 } 35 System.out.println("出現次數最多的數:" + num); 36 System.out.println("共出現" + maxCount + "次"); 37 38 } 39 40 public static void main(String[] args) { 41 int[] arr = {1,2,3,4,1,1,1,2,2,5,4,6,7,8,3,3,5,5,5,5,1,1,1}; 42 MaxCount(arr); 43 } 44 }

結果:

{1=7, 2=3, 3=3, 4=2, 5=5, 6=1, 7=1, 8=1}
出現次數最多的數:1
共出現7次

數組中出現最多的數,以及接口 Map.Entry<K,V>