如何找到最大值的数组索引?

时间:2014-04-07 11:55:25

标签: java arrays

上面的标题总结了我的问题,澄清了一个例子:

array[0] = 1
array[1] = 3
array[2] = 7  // largest
array[3] = 5

所以我想要的结果是2,因为它包含最大的元素7.

9 个答案:

答案 0 :(得分:11)

int maxAt = 0;

for (int i = 0; i < array.length; i++) {
    maxAt = array[i] > array[maxAt] ? i : maxAt;
}

答案 1 :(得分:7)

public int getIndexOfLargest( int[] array )
{
  if ( array == null || array.length == 0 ) return -1; // null or empty

  int largest = 0;
  for ( int i = 1; i < array.length; i++ )
  {
      if ( array[i] > array[largest] ) largest = i;
  }
  return largest; // position of the first largest found
}

答案 2 :(得分:2)

public int getIndexOfMax(int array[]) {
    if (array.length == 0) {
        return -1; // array contains no elements
    }
    int max = array[0];
    int pos = 0;

    for(int i=1; i<array.length; i++) {
        if (max < array[i]) {
            pos = i;
            max = array[i];
        }
    }
    return pos;
}

答案 3 :(得分:2)

一种方式是:

 Integer[] array = new Integer[4];
    array[0] = 1;
    array[1] = 3;
    array[2] = 7;
    array[3] = 5;

    List<Integer> iList = Arrays.asList(array);
    System.out.println(iList.indexOf(Collections.max(iList)));
    System.out.println(iList.indexOf(Collections.min(iList)));

答案 4 :(得分:1)

使用Java 8流:

    List<Integer> list = Arrays.asList(1, 3, 7, 5);
    IntStream.range(0, list.size())
            .reduce((i, j) -> list.get(i) > list.get(j) ? i : j)
            .getAsInt();

答案 5 :(得分:1)

两行代码将以高效的方式做到这一点

//find the maximum value using stream API of the java 8

Integer max =Arrays.stream(numbers) .max(Integer::compare).get();
// find the index of that value
int index  = Arrays.asList(numbers).indexOf(max);

答案 6 :(得分:0)

使用Arrays.sort(intArray)

int[] tempArray = myArray.clone();
Arrays.sort(tempArray );
int max = tempArray[tempArray .length - 1];
int result = Arrays.asList(myArray).indexOf(max );

答案 7 :(得分:0)

请在下面找到相同的代码

Integer array[] = new Integer[4];
array[0] = 1;
array[1] = 3;
array[2] = 7;
array[3] = 5;

List < Integer > numberList = Arrays.asList(array);

int index_maxNumber = numberList.indexOf(Collections.max(numberList));

System.out.println(index_maxNumber);

答案 8 :(得分:0)

另一个功能实现

int array[] = new int[]{1,3,7,5};        

int maxIndex =IntStream.range(0,array.length)
              .boxed()
              .max(Comparator.comparingInt(i -> array[i]))
              .map(max->array[max])
              .orElse(-1);