我对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;
}