Programmer = programming language basics + data structures + Algorithms
Over the past few days, I continue to return to the java basics and learn about the data structure. Here I will implement a simple algorithm-the algorithm for finding the number with the most appearance in the array
Public class HashMapTest1 {/*** find the number with the most numbers in an array * use the key of HashMap to store the numbers in the array, value stores the number of times this number appears in the array * @ author xiaoluo */public static void main (String [] args) {int [] array = {2, 1, 2, 3, 4, 5, 2, 2, 2, 2}; // The map key stores the numbers in the array, value stores the number of times this number appears in the array HashMap <Integer, Integer> map = new HashMap <Integer, Integer> (); for (int I = 0; I <array. length; I ++) {if (map. containsKey (array [I]) {int temp = map. get (array [I]); map. put (array [I], temp + 1);} else {map. put (array [I], 1) ;}} Collection <Integer> count = map. values (); // find the largest number in the map value, that is, the maximum number of times the number in the array appears int maxCount = Collections. max (count); int maxNumber = 0; for (Map. entry <Integer, Integer> entry: map. entrySet () {// obtain the key whose value is maxCount, that is, if (maxCount = entry. getValue () {maxNumber = entry. getKey () ;}} System. out. println ("the number that appears most frequently is:" + maxNumber); System. out. println ("this number appears in total" + maxCount + "times ");}}
The output is as follows:
The maximum number of occurrences is: 2. This number appears 6 times in total.