在 int 数组中,如何返回对应于最低值的索引?

我已经设法用“最低”变量找到数组中的最低值,但我正在寻找与数组中最低值相对应的索引。有任何想法吗?


public class Marathon {


    public static void main(String[] args) {


        String[] names = { "Elena", "Thomas", "Hamilton", "Suzie", "Phil", 

                           "Matt", "Alex", "Emma", "John", "James", "Jane",

                           "Emily", "Daniel", "Neda", "Aaron", "Kate" };


        int[] times = { 341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 

                        412, 393, 299, 343, 317, 265 };


        for (int i = 0; i < names.length; i++) {

            System.out.println(names[i] + ": " + times[i]);

        }

        lowesttime(names, times);

    }


    public static void lowesttime(String names[], int times[]) {

        int lowest;


        lowest = times[0];

        for (int i = 1; i < times.length; i++) {

            if (times[i] < lowest) {

                lowest = times[i];

            }

        }

        System.out.println(lowest);


        // to access arrays names[?], times[?}

        // System.out.println(names[lowest] + ": " + times[lowest]);

    }

}


汪汪一只猫
浏览 112回答 3
3回答

慕娘9325324

public static void lowesttime(String[] names, int[] times) {&nbsp; &nbsp; Pair<Integer, Integer> min = IntStream.range(0, times.length)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .mapToObj(i -> new Pair<Integer, Integer>(i, times[i]))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .reduce(new Pair<>(-1, Integer.MAX_VALUE), (r, p) ->&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; r.getKey() == -1 || r.getValue() > p.getValue() ? p : r);&nbsp; &nbsp; String minName = p.getKey() == -1 ? "nobody" : names[p.getKey()];&nbsp; &nbsp; System.out.printf("Found minimum for %s at index %d, value %d%n",&nbsp; &nbsp; &nbsp; &nbsp; minName, min.getKey(), min.getValue());}我想使用 Stream 来展示:IntStream.range(0, N)将给出 0, 1, 2, ..., N-1 的流。指数。mapToObj转换为 a&nbsp;Stream<Pair<Integer, Integer>>,其中对键是索引,对值是times[index]。reduce将以初始对(-1,Integer.MAX_VALUE)作为结果开始,然后对于流中的每一对是否可以找到更好的最小值。请注意,您可以只使用一对名称和时间 (&nbsp;Pair<String, Integer>);不需要索引。这里可能过于高级和具体,但它非常具有表现力和干净(使用步骤而不需要局部变量)。

蝴蝶不菲

您可以将变量设置为元素的索引,而不仅仅是获取该元素的值;public static void lowesttime(String[] names, int[] times) {&nbsp; &nbsp; int lowest;&nbsp; &nbsp; int lowestIndex = 0;&nbsp; &nbsp; lowest = times[0];&nbsp; &nbsp; for (int i = 1; i < times.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (times[i] < lowest) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lowest = times[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lowestIndex = i;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(lowest);&nbsp; &nbsp; System.out.println(lowestIndex);&nbsp; &nbsp; // to access arrays names[?], times[?}&nbsp; &nbsp; // System.out.println(names[lowest] + ": " + times[lowest]);}

呼唤远方

如果您已经知道最低值,则可以使用:java.util.Arrays.asList(theArray).indexOf(lowestValue)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java