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

package learning.Test;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lhx
 * @date 2022/9/24 8:00
 * @describe 使用HashMap,每个Entry的key存放数组中的数字,value存放该数字出现的次数,
 * 首先遍历数组元素构造HashMap,然后遍历每个Entry,
 * 找出最大value对应的key,即是出现次数最多的那个数。此算法的时间复杂度为O(n)
 */
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);
            } 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为maxCont的key,也就是数组中出现次数最多的数字
            if (entry.getValue() == maxCount) {
                maxNumber = entry.getKey();
            }
        }
        System.out.println("出现次数最多的数字为:" + maxNumber);
        System.out.println("该数字一共出现" + maxCount + "次");
    }

    //找出出现次数最多的数字 方法二
    public static void candidate2 (int[] array)    // 找出数组中出现次数最多的那个数
    {

        //求最大值,得出数组长度
        int max = 0;

        //遍历求最大值
        for (int i = 0; i < array.length; i++) {
            max = Math.max(max, array[i]);
        }
        int[] count = new int[max + 1];

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

    public static void main(String[] args) {
        int[] array = {23, 56, 852, 45, 32, 125, 235, 121, 12, 12, 23, 32, 12, 55};
        candidate2(array);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值