[英]How would I find the index of the smallest value in an int array?
我对java还是很陌生,所以我想保持简单,我想我必须采用数组的第一个值,然后将其与每个后续值进行比较,如果该值大于第一个值,则替换价值,但我不知道如何从中获取索引。
对于一个非结构化,未排序的数组,假设仅要查找一次最小值,那么您可以做的最好的事情是对所有元素进行一次简单的迭代( O(n)复杂度),如下所示:
public int findMinIdx(int[] numbers) {
if (numbers == null || numbers.length == 0) return -1; // Saves time for empty array
// As pointed out by ZouZou, you can save an iteration by assuming the first index is the smallest
int minVal = numbers[0] // Keeps a running count of the smallest value so far
int minIdx = 0; // Will store the index of minVal
for(int idx=1; idx<numbers.length; idx++) {
if(numbers[idx] < minVal) {
minVal = numbers[idx];
minIdx = idx;
}
}
return minIdx;
}
同样,如果为最小值,则此方法将返回找到的该值的第一种情况的索引。 如果希望它是最后一种情况,只需将numbers[idx] < minVal
为numbers[idx] <= minVal
。
这是Java 8
public static int findMinIdx(int[] numbers) {
OptionalInt minimun = IntStream.of(numbers).min();
return IntStream.of(numbers).boxed().collect(toList()).indexOf(minimun.getAsInt());
}
从不关心运行时优化,只是在寻找解决方案!,它奏效了,这对您也有帮助,可以找到数组中最低值的索引。
// array[] -> Received the array in question as an parameter
// index -> stores the index of the lowest value
// in for loop, i is important to complete all the comparison in the function
// When it finds a lower value between the two, it does not change the index
// When it finds a lower value it changes it's index to that index
// If array has same value more than once, it will provide index to that values last occurrence
// Correct me if you find anything not working in this example...
//...
private static int index_of_minimum_value(int[] array) {
int index = 0;
for (int i = 1; i < array.length; i++) {
if ((array[i - 1] < array[i]) && ([index] > array[i - 1])) index = i - 1;
else if (array[index] > array[i]) index = i;
}
return index;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.