【算法笔记之数组】找出数组中出现次数最多的数

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

法一: 遍历计数法

    //找出出现次数最多的数字 方法一
    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 + "次");
    }

法二: 利用map实现

    //找出出现次数最多的数字 方法二 O(n)
    public static void candidate2 (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 + "次");
    }
  • 4
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值