[英]Index of Highest element in an array
我有一個名為“ indexOfMaxInRange”的方法,並且構建了大部分代碼,但是,我感覺有些問題。 目的是遍歷數組,並返回數組中最高元素的索引。 這是代碼
public static int indexOfMaxInRange(int[] a,int low, int high)
{int[] count=a;int index=0;
for(int i=0;i<count.length;i++)
{if(a[i]>low&&a[i]<high)index++;}
return index;}
在大多數情況下,我已經進行了設置,我覺得需要做更多的工作,並對代碼進行一些編輯。 有什么建議么?
也許這將有助於找到最大元素的索引
public static int indexOfMaxInRange(int[] a,int low, int high)
{
int index=-1;
int max=0;
for(int i=0;i<a.length;i++)
{if(a[i]>max)
{
max=a[i];
index=i;
}
}
return index;
}
public static int indexOfMaxInRange(int[] a , int low , int high){
if(high >= a.length)
throw new IllegalArgumentException("High must be smaller than arraylength");
if(low < 0)
throw new IllegalArgumentException("Low must be > 0");
if(low > high)
throw new IllegalArgumentException("Low must be > High");
if(a.length == 0)
return -1;
int index = low;
for(int i = low ; i < high ; i++)
if(a[index] < a[i])
index = i;
return index;
}
這個怎么樣:
public static int indexOfMaxInRange(int[] a) {
int index=0;
int largest=0;
for (int i=0; i < a.length; ++i) {
if (a[i] > largest) {
largest = a[i];
index = i;
}
}
return index;
}
考慮以下代碼:
int largest = 0, index = 0;
for (int i = 1; i < array.length; i++) {
if ( array[i] >= largest ) {
largest = array[i];
index = i;
}
}
return index;
public static int indexOfMax(int[] arr) {
int index=0;
int max=0;
for (int i=0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
index = i;
}
}
return index;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.