A simple algorithm is used to find the number with the largest number in the array.

Source: Internet
Author: User

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.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.