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 the result I would like is 2, since it contains the largest element 7.
所以我想要的结果是2,因为它包含最大的元素7。
5 个解决方案
#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
9
int maxAt = 0;
for (int i = 0; i < array.length; i++) {
maxAt = array[i] > array[maxAt] ? i : maxAt;
}
#3
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;
}
#4
1
one way will be:
一种方式是:
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)));
#5
0
int[] tempArray = myArray.clone();
Arrays.sort(tempArray );
int max = tempArray[tempArray .length - 1];
int result = Arrays.asList(myArray).indexOf(max );
#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
9
int maxAt = 0;
for (int i = 0; i < array.length; i++) {
maxAt = array[i] > array[maxAt] ? i : maxAt;
}
#3
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;
}
#4
1
one way will be:
一种方式是:
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)));
#5
0
int[] tempArray = myArray.clone();
Arrays.sort(tempArray );
int max = tempArray[tempArray .length - 1];
int result = Arrays.asList(myArray).indexOf(max );