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

时间:2015-02-18 17:04:44

标签: java arrays

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

3 个答案:

答案 0 :(得分: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;
}

此外,在最小值为tie的情况下,此方法将返回它找到的值的 first 大小写的索引。如果您希望它是 last 的情况,只需将numbers[idx] < minVal更改为numbers[idx] <= minVal

答案 1 :(得分: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());
    }

答案 2 :(得分: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;
}