问题描述
我不知道如何获得数组中最大和最小数字的索引位置。有人可以帮助我吗? 我的代码:
int[] array = {4,2,7,6,-3,-1,-2,42,-42,9,-4,5,-5,-6,-7,-8,-99,11,20,1,3};
int smallest = array[0];
int largest = array[0];
for (int i = 1; i < array.length; i++){
if (array[i] > largest) {
largest = array[i];
} else if (array[i] < smallest)
smallest = array[i];
}
System.out.println("Largest: " + largest);
System.out.println("Smallest: " + smallest);
我已经有了最大和最小的数字,但我如何找到索引位置。
解决方法
再创建两个变量来存储最大索引和最小索引,现在每当您在 if-else 语句中为最小和最大分配新值时,也会分配 i 的值。
int smallestInd = 0;
int largestInd = 0;
for (int i = 1; i < array.length; i++){
if (array[i] > largest) {
largest = array[i];
largestInd = i;
} else if (array[i] < smallest)
smallest = array[i];
smallestInd = i;
}
,
这应该有效
int[] array = {4,2,7,6,-3,-1,-2,42,-42,9,-4,5,-5,-6,-7,-8,-99,11,20,1,3};
int si,smallest = array[si = 0];
int li,largest = array[li = 0];
for (int i = 1; i < array.length; i++) {
if (array[i] > largest) {
largest = array[li = i];
} else if (array[i] < smallest) {
smallest = array[si = i];
}
}
System.out.println("Largest: " + li);
System.out.println("Smallest: " + si);
或更容易阅读:
int[] array = {4,3};
int si = 0,smallest = array[0];
int li = 0,largest = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > largest) {
largest = array[i];
li = i;
} else if (array[i] < smallest) {
smallest = array[i];
si = i;
}
}
System.out.println("Largest: " + li);
System.out.println("Smallest: " + si);
,
这是一个有趣的方法,但它不是很有效,因为它需要对值进行排序。基本上,生成所有可能的索引,然后根据实际数组值对它们进行排序。结果数组的第一个和最后一个元素将分别是最小和最大位置。
int[] array = { 4,3 };
Integer[] arr = IntStream.range(0,array.length).boxed()
.sorted(Comparator.comparingInt(a -> array[a]))
.toArray(Integer[]::new);
System.out.println("Index for min = " + arr[0]);
System.out.println("Index for max = " + arr[arr.length-1]);
印刷品
Index for min = 17
Index for max = 18
,
I was able to came up with two answers :
ary.sort();
console.log(
`This is max ${ary[0]} of the numbers and here is ${
ary[-1]
} the min of the numbers list!`
);
_________________________________________________________________
` let ary = [8,13,44,55];
let max = ary[0];
let min = ary[0];
let locationMax,locationMin;
for (i = 0; i <= ary.length; i++) {
if (ary[i] > max) {
max = ary[i];
locationMax = i;
} else if (ary[i] < min) {
min = ary[i];
locationMin = i;
}
}
console.log(
`This is the location of the max ${locationMax} so The second location number ${locationMin} is for min!`
);