实现的方法有很多,以下是一次遍历就能实现的方法
public static void main(String[] args) {
// 以什么格式输入就用什么方法解析数据
// String line;
// Scanner sc = new Scanner(System.in);
// line = sc.nextLine();
// String[] split = line.split(",");
Integer[] array = {15,1,2,5,1,3,5,4,12,15};//要操作的数组
System.out.println( getMostInteger( array ) );
// sc.close();
}
public static String getMostInteger( Integer[] arrayMath ){
//key保存出现过的数字,value保存形式为 下标_出现次数长度的字符。
Map<Integer , String> m = new HashMap<>();
int max = 1;//保存最大出现的次数
int minIndex = 0;//保存最大数的下标
for( int i = 0 ; i < arrayMath.length ; i ++ ){
if( m.containsKey( arrayMath[i] ) ){
m.put( arrayMath[i] , m.get( arrayMath[i] ) + 1 );
String[] s = m.get(arrayMath[i]).split("_");//将索引和出现次数分离
int length = s[1].length();//获取出现次数
if( length > max ){
max = length;
minIndex = Integer.parseInt( s[0] );
}else if( length == max ){
if( Integer.parseInt( s[0] ) < minIndex ){
minIndex = Integer.parseInt( s[0] );
}
}
}else {
m.put( arrayMath[i] , i + "_" + 1 );
}
}
String result = "出现次数最多的是" + arrayMath[minIndex] + "出现的次数为" + max;
return result;
}