简体   繁体   English

查找数组中的最高索引值

[英]Find highest index value in array

Hello I want find the highest index n array.你好我想找到最高索引 n 数组。 For example I have two arrays : [1,2,3,0,-1] - should return 2 - index with max values [] - should return -1 because array is empty例如,我有两个数组: [1,2,3,0,-1] - 应该返回 2 - 具有最大值的索引 [] - 应该返回 -1 因为数组是空的

I have method:我有方法:

   public int findMax(int[] array){
    int values =0;
    for(int i=0; i<array.length; i++){
    if(array == null)
    {return -1;}
    else(array{i}>values){
    return i;
    }
 }

What i'm doing wrong?我在做什么错?

Your program has logical as well as compilation errors.您的程序存在逻辑错误和编译错误。 I guess you want to write a code like this,我猜你想写这样的代码,

public static void main(String[] args) throws IOException {
    System.out.println(findMax(new int[] { 1, 2, 3, 0, -1 }));
    System.out.println(findMax(new int[] {}));
}

public static int findMax(int[] array) {
    if (array == null || array.length == 0) {
        return -1;
    }

    int maxIndex = 0;
    int maxNum = array[0];
    for (int i = 1; i < array.length; i++) {
        if (array[i] > maxNum) {
            maxNum = array[i];
            maxIndex = i;
        }
    }

    return maxIndex;
}

Like you expected, this gives following output,正如您所料,这给出了以下输出,

2
-1

Suppose you want to find both maximum element and first index of maximum value.假设您要查找最大元素和最大值的第一个索引。

Code for this:代码

public void findMax(int[] array){
    int values =-99999999; //values is any large negative number
    int index=-1;
    if(array.length == 0)
    {System.out.println("-1");}
    for(int i=0; i<array.length; i++){
    if(array[i]>values){ 
       values=array[i];
       index=i;
      }
    System.out.println("Max element is"+values +"and index is"+index);
    }
 }

Try this one:试试这个:

public int findMax(int[] array) {
    if (array == null || array.length == 0)
        return -1;

    int index = 0;
    int max = -Integer.MAX_VALUE;
    for (int i=0; i< array.length; i++) {
        if (array[i] > max) {
            index = i;
            max = array[i];
        }
    }

    return index;
}
public int findMax(int[] array){
    return IntStream.range(0, array.length).boxed().max(Comparator.comparing(i -> array[i])).orElse(-1));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM