Java 查找整型数组中最大值的下标(包含多个最大值)
以下是一个 Java 方法,可以找出整型数组中的最大值的下标,即使存在多个最大值:
public static int[] findMaxIndex(int[] array) {
int max = Integer.MIN_VALUE;
int count = 0;
// 遍历数组,找出最大值
for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
count = 1;
} else if (array[i] == max) {
count++;
}
}
// 创建一个数组来存储最大值的下标
int[] indexes = new int[count];
int index = 0;
// 再次遍历数组,记录最大值的下标
for (int i = 0; i < array.length; i++) {
if (array[i] == max) {
indexes[index] = i;
index++;
}
}
return indexes;
}
你可以使用该方法来查找整型数组中的最大值的下标。例如:
int[] array = {1, 3, 5, 5, 2, 4, 5};
int[] indexes = findMaxIndex(array);
for (int i = 0; i < indexes.length; i++) {
System.out.println('最大值的下标为:' + indexes[i]);
}
输出结果为:
最大值的下标为:2
最大值的下标为:3
最大值的下标为:6
请注意,如果数组中存在多个最大值,该方法将返回所有最大值的下标。
原文地址: https://www.cveoy.top/t/topic/qeas 著作权归作者所有。请勿转载和采集!