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);
}
}
06-30
3105
04-27
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交