如何在int数组中找到最小值的索引?

问题描述 投票:1回答:3

我对java很新,所以我想保持简单,我想我必须取数组的第一个值然后将它与每个后续值进行比较,如果该值大于第一个值,则替换它的价值,但我不知道如何从中得到索引。

java arrays
3个回答
5
投票

对于非结构化,未排序的数组,您可以做的最好,假设您只需要找到一次最小值,就是对所有元素(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


3
投票

这是Java 8

 public static int findMinIdx(int[] numbers) {
        OptionalInt minimun = IntStream.of(numbers).min();
        return   IntStream.of(numbers).boxed().collect(toList()).indexOf(minimun.getAsInt());
    }

0
投票

从来没有关心运行时优化,只是在寻找解决方案!,这很有用,这对你也有帮助,找到数组中最低值的索引。

    // 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;
}
© www.soinside.com 2019 - 2024. All rights reserved.