[英]How to find array index of largest value?
上面的標題總結了我的問題,為了澄清一個例子是:
array[0] = 1
array[1] = 3
array[2] = 7 // largest
array[3] = 5
所以我想要的結果是 2,因為它包含最大的元素 7。
int maxAt = 0;
for (int i = 0; i < array.length; i++) {
maxAt = array[i] > array[maxAt] ? i : maxAt;
}
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
}
一種方法是:
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)));
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;
}
使用 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();
兩行代碼將以有效的方式做到這一點
//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);
請在下面找到相同的代碼
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);
int[] tempArray = myArray.clone();
Arrays.sort(tempArray );
int max = tempArray[tempArray .length - 1];
int result = Arrays.asList(myArray).indexOf(max );
另一個功能實現
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);
會這樣做(因為我不知道任何預定義的函數來獲取最高元素的索引,只有元素本身,當然你可以使用list.indexOf(element)
獲取索引,但是需要轉換數組列出和 2 次迭代):
maxIndex = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] > array[maxIndex]) {
maxIndex = i;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.