How to find array index of largest value?

后端 未结 8 1253
小蘑菇
小蘑菇 2020-12-11 02:33

The title above sums up my question, to clarify things an example is:

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

so th

相关标签:
8条回答
  • 2020-12-11 02:33
    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
    }
    
    0 讨论(0)
  • 2020-12-11 02:35

    Another functional implementation

    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);
    
    0 讨论(0)
  • 2020-12-11 02:39

    Two lines code will do that in efficient way

    //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);
    
    0 讨论(0)
  • 2020-12-11 02:40

    Please find below code for the same

    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);
    
    0 讨论(0)
  • 2020-12-11 02:43
    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;
    }
    
    0 讨论(0)
  • 2020-12-11 02:47
    int maxAt = 0;
    
    for (int i = 0; i < array.length; i++) {
        maxAt = array[i] > array[maxAt] ? i : maxAt;
    }
    
    0 讨论(0)
提交回复
热议问题