数组最大值的索引



我需要通过将可变长度数组传递到方法中来返回整数数组最大值的索引。 如何遍历数组然后返回一个或多个值

到目前为止,我拥有的:

public static int methodname3(int d[]) { //separate method with array
    int largest = 0;
    int index = 0;
    for (int i = 0; i < d.length; i++) {
        if ( d[i] > largest ) 
        {
           largest = d[i];
           index = i;
        }
    }
    return index;
}

如果你需要返回多个索引,你需要的不仅仅是一个整数。根据您计划之后如何处理数据,我建议返回数组String,然后将该值传递给另一种方法进行处理。

我建议将问题分为两部分,首先查找并计算最大值的实例数,然后抓取最大值的索引。如果要返回数组中的索引,则需要单步执行两次(这是使用标准数组,而不是可扩展的 ArrayLists)。如果要将索引作为字符串返回,则只需执行一次传递。

public static int[] methodname3(int d[]) {
    int largest = d[0] - 1; // this makes sure that negative values are checked
    int instances = 0;
    int[] indices = null;
    for (int i = 0; i < d.length; i++){
        if (d[i] > largest){
            largest = d[i];
            instances = 1;
        }
        else if(d[i] == largest){
            instances++;
        }
    }
    indices = new int[instances];
    for(int i = 0, j = 0; i < d.length; i++){
        if(d[i] == largest){
            indices[j] = i;
            j++;
        }
    }
    return indices;
}

如果要将索引作为字符串返回,则可以像这样一次性完成整个操作:

public static String methodname3(int d[]){
    int largest = d[0] - 1;
    String indices = "";
    for (int i = 0; i < d.length; i++){
        if (d[i] > largest){
            largest = d[i];
            indices = i; // This resets the String each time a larger value is found
        }
        else if(d[i] == largest){
            indices = indices + " " + i; 
            // This results in a space delimited String of indices
        }
    }
    return indices;
}

按照上面的方法,它是: 返回一个包含索引的列表

public List<Integer> methodname3(int d[])  //separate method with array
    {     
        int largest = 0;
        List<Integer> index = new ArrayList<Integer>();
    for (int i = 0; i < d.length; i++) {
        if ( d[i] > largest ) 
        {
            largest = d[i];
            index.add(i);
        }
    }
    return index;
}

这将起作用。正如您所说,您的输入可以有多个max值,并且您想从您的方法中return一些东西,您应该考虑某种形式的列表(我使用了ArrayList)。在main只需iterate列表并打印值即可。

public static ArrayList<Integer> getIndices(int[] arr) {
        ArrayList<Integer> output = new ArrayList<Integer>();
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }
        for (int j = 0; j < arr.length; j++) {
            if (arr[j] == max) {
                output.add(j);
            }
        }
        return output;
    }

我的建议是不要使用 int index,而是使用整数数组,在循环时将索引添加到数组中,然后返回数组。

像这样:

        public static int methodname3(int d[])  //separate method with array
    {     
        int largest = 0;
        int index[];
        int c = 0;
    for (int i = 0; i < d.length; i++) {
        if ( d[i] > largest ) 
        {
            largest = d[i];
            index[c] = i;
            c++;
        }
    }
    return index[];
}

最新更新