Java-實現找出陣列中一個數字出現次數最多的數字
阿新 • • 發佈:2019-02-07
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class Mytest
{
/**
* @param args
*/
public static void main(String[] args)
{
int[] array = {2,3,1,2,2,5,6,8,2,3,2,4,2};
HashMap<Integer, Integer> map = new HashMap<>();//第一個值為出現的數字,第二個值為出現的次數
for (int i = 0; i < array.length; i++)
{
if(map.containsKey(array[i]))
{
int temp = map.get(array[i]);
map.put(array[i],temp+1);
}
else
{
map.put(array[i],1);
}
int maxCount = Collections.max(count);
int maxnum = 0;
for (Map.Entry<Integer,Integer> entry:map.entrySet())
{
if (maxCount==entry.getValue())
{
maxnum = entry.getKey();
}
}
System.out.println("出現次數最多的數字為"+maxnum);
System.out.println("改次數一共出現了"+maxCount+"次");
}
}
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class Mytest
{
/**
* @param args
*/
public static void main(String[] args)
{
int[] array = {2,3,1,2,2,5,6,8,2,3,2,4,2};
HashMap<Integer, Integer> map = new HashMap<>();//第一個值為出現的數字,第二個值為出現的次數
for (int i = 0; i < array.length; i++)
{
if(map.containsKey(array[i]))
{
int temp = map.get(array[i]);
map.put(array[i],temp+1);
}
else
{
map.put(array[i],1);
}
}
//得到value為maxCount的key,也就是陣列中出現次數最多的數字Collection<Integer> count = map.values();
int maxCount = Collections.max(count);
int maxnum = 0;
for (Map.Entry<Integer,Integer> entry:map.entrySet())
{
if (maxCount==entry.getValue())
{
maxnum = entry.getKey();
}
}
System.out.println("出現次數最多的數字為"+maxnum);
System.out.println("改次數一共出現了"+maxCount+"次");
}
出現次數最多的數字為2
改次數一共出現了6次
}