Java 如何获得数组中相同大数的多个索引?
我正在尝试获取数组中大数的索引,但在这样做时遇到了困难。。 如果数组中只有一个大数字,我的代码就可以工作。但是,如果有一个或多个相同的大数字,则它不起作用 比如说,Java 如何获得数组中相同大数的多个索引?,java,arrays,Java,Arrays,我正在尝试获取数组中大数的索引,但在这样做时遇到了困难。。 如果数组中只有一个大数字,我的代码就可以工作。但是,如果有一个或多个相同的大数字,则它不起作用 比如说, 如果我有一个数组{2,1,1,2,1},它应该返回索引0和3(这不是) 如果我有一个数组{2,1,3,2,1},它将返回索引2。(本工程) 目前,我试图通过使用数组来存储索引,但是在我的代码中,如上面的示例所示,它只返回它找到的第一个大数字的索引 我的代码: class Main { public static void ge
- 如果我有一个数组
,它应该返回索引0和3(这不是){2,1,1,2,1}
- 如果我有一个数组
,它将返回索引2。(本工程){2,1,3,2,1}
class Main {
public static void getIndexOfMax(int array[]) {
int max = array[0];
int pos = 0;
int max_index[] = new int[array.length];
int counter = 0;
for(int i=1; i<array.length; i++) {
if (max < array[i])
{
pos = i;
max = array[i];
max_index[counter] = pos;
counter += 1;
}
}
public static void main(String[] args) {
int[] num = {2,1,1,2,1};
getIndexOfMax(num);
}
}
主类{
公共静态void getIndexOfMax(int数组[]){
int max=数组[0];
int pos=0;
int max_index[]=新的int[array.length];
int计数器=0;
对于(inti=1;i可以使用另一个条件语句,如果max等于数组元素,那么也存储该元素索引。然后必须为max索引位置声明另一个数组。
`if(最大值<数组[i]){
pos=i
indexStorage.add(位置)
max=数组[I]
最大索引[计数器]=位置
计数器+=1;
}`当您再次找到最大值并存储索引时,需要检查另一种情况。当新的最大值再次从0开始计数器
public static void printIndexOfMax(int array[]) {
int max = 0;
int max_index[] = new int[array.length];
int counter = 0;
for (int i = 0; i < array.length; i++) {
if (max <= array[i]) { // Allowing same maximum number
if (max < array[i]) // Start counter from 0 when new maximum value found
counter = 0;
max = array[i];
max_index[counter] = i;
counter++;
}
}
for (int i = 0; i < counter; i++) {
System.out.println(max_index[i]);
}
}
publicstaticvoid printIndexOfMax(int数组[]){
int max=0;
int max_index[]=新的int[array.length];
int计数器=0;
for(int i=0;i 如果(最大重复的希望它的工作,如果不让我知道。谢谢你,没有想过使用计数器重新检查它是否是相同的最大数字。