如何找到最大的数组索引? [英] How to find array index of largest value?
本文介绍了如何找到最大的数组索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
上面的标题总结了我的问题,以澄清一个例子:
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
所以我想要的结果是2,因为它包含最大的元素7.
so the result I would like is 2, since it contains the largest element 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
}
这篇关于如何找到最大的数组索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文