您的位置:首页 > 编程语言 > Java开发

Java - 求数组中最大值(个数不确定)及其下标

2018-01-05 14:29 330 查看

利用 Map,遍历一次即可获得数组中最大值的同时,也获得最大值的数组下标。

package com.code.ggsddu;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class ArrayMaxAndIndexes {
public static void main(String[] args) {
int[] arr0 = {2, 2, 2, 2, 2};
int[] arr1 = {2, 3, 5, 4, 3};
int[] arr2 = {3, 3, 5, 5, 5};
int[] arr3 = {1, 2, 3, 5, 5};
int[] arr4 = {5, 4, 2, 5, 5};
System.out.println(Arrays.toString(arr0));
getMaxValuesAndIndexes(arr0);
System.out.println("--------------------");
System.out.println(Arrays.toString(arr1));
getMaxValuesAndIndexes(arr1);
System.out.println("--------------------");
System.out.println(Arrays.toString(arr2));
getMaxValuesAndIndexes(arr2);
System.out.println("--------------------");
System.out.println(Arrays.toString(arr3));
getMaxValuesAndIndexes(arr3);
System.out.println("--------------------");
System.out.println(Arrays.toString(arr4));
getMaxValuesAndIndexes(arr4);
}

public static void getMaxValuesAndIndexes(int[] arr) {
Map<String, Object> map = new HashMap<>();
int max = arr[0];
map.put("indexes", 0);
for (int i = 1; i < arr.length; i++) {
int temp = arr[i];
if (max == temp) {
map.put("indexes", map.get("indexes") + "," + i);
} else if (max < temp) {
max = temp;
map.put("indexes", i);
}
}
System.out.println("max: " + max);
System.out.println("indexes: " + map.get("indexes"));
String[] indexesArray = map.get("indexes").toString().split(",");
System.out.println("indexesArray: " + Arrays.toString(indexesArray));
}
}


控制台打印结果:

[2, 2, 2, 2, 2]
max: 2
indexes: 0,1,2,3,4
indexesArray: [0, 1, 2, 3, 4]
--------------------
[2, 3, 5, 4, 3]
max: 5
indexes: 2
indexesArray: [2]
--------------------
[3, 3, 5, 5, 5]
max: 5
indexes: 2,3,4
indexesArray: [2, 3, 4]
--------------------
[1, 2, 3, 5, 5]
max: 5
indexes: 3,4
indexesArray: [3, 4]
--------------------
[5, 4, 2, 5, 5]
max: 5
indexes: 0,3,4
indexesArray: [0, 3, 4]

Process finished with exit code 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java 遍历 数组 最大值
相关文章推荐