当前位置:网站首页>找数组中出现次数最多的数
找数组中出现次数最多的数
2022-07-24 05:20:00 【一枚小可爱c】
使用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 + "次");
}
}边栏推荐
- 国内外知名源码商城系统盘点
- How to quickly recover data after MySQL misoperation
- ntp错误: no server suitable for synchronization found
- The method of using bat command to quickly create system restore point
- 【activiti】activiti流程引擎配置类
- 《机器学习》(周志华) 第3章 线性模型 学习心得 笔记
- 使用bat命令快速创建系统还原点的方法
- 目标检测带标签数据增强代码
- Multi merchant mall system function disassembly lecture 06 - platform side merchant settlement agreement
- 达梦数据库_触发器、视图、物化视图、序列、同义词、自增列、外部链接等基本的操作
猜你喜欢

多商户商城系统功能拆解03讲-平台端商家管理

多商户商城系统功能拆解13讲-平台端会员管理

Connect CRM system and effect advertising, help enterprises with precision marketing, and help enterprises with precision marketing

Multi merchant mall system function disassembly lecture 06 - platform side merchant settlement agreement

《统计学习方法(第2版)》李航 第22章 无监督学习方法总结 思维导图笔记

在网络中添加SE通道注意力模块

likeshop单商户商城系统搭建,代码开源无加密

Inventory of well-known source code mall systems at home and abroad

likeshop单商户SAAS商城系统无限多开

likeshop单商户SAAS商城系统搭建,代码开源无加密。
随机推荐
【mycat】mycat介绍
Numpy数组广播规则记忆方法 array broadcast 广播原理 广播机制
【activiti】activiti环境配置
The SaaS mall system of likeshop single merchant is built, and the code is open source without encryption.
ThreadLocal stores the current login user information
Multi merchant mall system function disassembly lecture 06 - platform side merchant settlement agreement
数据集成的两种架构:ELT和ETL
Canal+kafka实战(监听mysql binlog实现数据同步)
Zotero快速上手指南
第五章神经网络
Flink Format系列(1)-JSON
如何快速打通CRM系统和ERP系统,实现业务流程自动化流转
《机器学习》(周志华)第一章 绪论 笔记 学习心得
达梦数据库_在使用过程中的需要注意的小事项
Detailed discussion on data synchronization tools ETL, ELT, reverse ETL
Multi merchant mall system function disassembly Lecture 10 - platform end commodity units
Mysqldump export Chinese garbled code
达梦数据库_dmfldr工具使用说明
达梦数据库_常用命令
Sqlserver completely deleted