一個簡單的算法---實現找出數組中一個數字出現次數最多的數字


程序員=編程語言基礎+數據結構+算法

這幾天繼續回歸java基礎,以及學習數據結構的知識,這里實現一個簡單的算法----找出數組中一個數字出現次數最多的數字的算法

 

public class HashMapTest1
{
    /**
     * 找出一個數組中一個數字出現次數最多的數字
     * 用HashMap的key來存放數組中存在的數字,value存放該數字在數組中出現的次數
     * @author xiaoluo 
     */
    public static void main(String[] args)
    {
        int[] array = {2, 1, 2, 3, 4, 5, 2, 2, 2, 2};
        
        //map的key存放數組中存在的數字,value存放該數字在數組中出現的次數
        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();
        
        //找出map的value中最大的數字,也就是數組中數字出現最多的次數
        int maxCount = Collections.max(count);
        
        int maxNumber = 0;
        
        for(Map.Entry<Integer, Integer> entry : map.entrySet())
        {
            //得到value為maxCount的key,也就是數組中出現次數最多的數字
            if(maxCount == entry.getValue())
            {
                maxNumber = entry.getKey();
            }
        }
        
        System.out.println("出現次數最多的數字為:" + maxNumber);
        System.out.println("該數字一共出現" + maxCount + "次");
    }
}

 

打印結果如下:

出現次數最多的數字為:2
該數字一共出現6次

 

 


免責聲明!

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



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