首页 > 编程语言 > 详细

找出数组中出现次数最多的那个数

时间:2016-03-19 21:17:53      阅读:156      评论:0      收藏:0      [点我收藏+]

 

  方法一:以空间换时间,可以定义一个计数数组int count[101],用来对数组中数字出现的次数进行计数(只能针对数组中数字的范围1~100),count数组中最大的元素对应的下标,即为出现次数最多的那个数。Java代码如下:

public class SearchMuch {

    public static void candidate (int[] array)    // 找出数组中出现次数最多的那个数
    {
        int[] count = new int[101];                // 计数数组,每个元素的默认值为0
        for(int i = 0; i < array.length; i++)
        {
            count[array[i]]++;                    // 对应的计数值加1
        }
        int maxCount = count[0];
        int maxNumber = 0;
        for(int i = 1; i < 100; i++)            // 找出最多出现的次数
        {
            if(count[i] > maxCount)
                maxCount = count[i];
        }
        for(int i = 0; i < 100; i++)            // 找出出现最多次的那个数字
        {
            if(count[i] == maxCount)
                maxNumber = i;
        }
        System.out.println("出现次数最多的数字为:" + maxNumber);
        System.out.println("该数字一共出现" + maxCount + "次");
    }
}

 

  上例是一种典型的空间换时间算法(所需数组空间的大小完全取决于数组中数字的大小)。一般情况下,除非内存空间足够大且数组中的数不是很大,否则一般不采用这种方法。

 

  方法二:使用HashMap,每个Entry的key存放数组中的数字,value存放该数字出现的次数,首先遍历数组元素构造HashMap,然后遍历每个Entry,找出最大value对应的key,即是出现次数最多的那个数。此算法的时间复杂度为O(n)。Java代码如下:

public class SearchMuch {

    public static void candidate (int[] array)    // 找出数组中出现次数最多的那个数
    {
        // 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 formerValue = map.get(array[i]);
                map.put(array[i], formerValue + 1);    // 该数字出现的次数加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(entry.getValue() == maxCount)
            {
                maxNumber = entry.getKey();
            }
        }
        System.out.println("出现次数最多的数字为:" + maxNumber);
        System.out.println("该数字一共出现" + maxCount + "次");
    }
}

 

找出数组中出现次数最多的那个数

原文:http://www.cnblogs.com/eniac12/p/5296139.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!