java 定义一个方法找出一个整型数组中的最大值的下标注意最大值可能有多个
可以定义一个方法来实现这个功能:
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5, 5, 4, 3, 2, 1};
int[] maxIndexes = findMaxIndexes(array);
System.out.println("最大值的下标为:");
for (int index : maxIndexes) {
System.out.println(index);
}
}
public static int[] findMaxIndexes(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[] maxIndexes = new int[count];
int currentIndex = 0;
// 再次遍历数组,找出最大值的下标
for (int i = 0; i < array.length; i++) {
if (array[i] == max) {
maxIndexes[currentIndex] = i;
currentIndex++;
}
}
return maxIndexes;
}
}
在上述代码中,我们首先定义了一个 findMaxIndexes 方法,它接受一个整型数组作为参数,并返回一个整型数组。在该方法中,我们使用了两次循环来实现功能。
第一次循环用于找出数组中的最大值,我们使用了两个变量 max 和 count,其中 max 用于保存当前找到的最大值,count 用于记录最大值出现的次数。
第二次循环用于找出最大值的下标,我们首先创建了一个长度为 count 的整型数组 maxIndexes,用于保存最大值的下标。然后再次遍历数组,如果当前元素的值等于最大值,就将当前下标保存到 maxIndexes 数组中。
最后,在 main 方法中我们定义了一个示例数组,并调用 findMaxIndexes 方法来找到最大值的下标,并输出结果
原文地址: https://www.cveoy.top/t/topic/iwHT 著作权归作者所有。请勿转载和采集!