有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我已经用我的“lowest”变量找到了数组中的最低值,但我正在寻找对应于数组中最低值的索引。有什么想法吗

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]);
    }
}

共 (3) 个答案

  1. # 1 楼答案

    public static void lowesttime(String[] names, int[] times) {
        Pair<Integer, Integer> min = IntStream.range(0, times.length)
                .mapToObj(i -> new Pair<Integer, Integer>(i, times[i]))
                .reduce(new Pair<>(-1, Integer.MAX_VALUE), (r, p) ->
                    r.getKey() == -1 || r.getValue() > p.getValue() ? p : r);
    
        String minName = p.getKey() == -1 ? "nobody" : names[p.getKey()];
        System.out.printf("Found minimum for %s at index %d, value %d%n",
            minName, min.getKey(), min.getValue());
    }
    

    我想展示一下如何使用流:

    • IntStream.range(0, N)将给出一个0,1,2。。。,N-1。指数
    • mapToObj转换为Stream<Pair<Integer, Integer>>,其中pairs键是索引,pairs值是times[index]
    • reduce将以一个初始对(-1,Integer.MAX_VALUE)开始, 然后,对于流中的每一对,是否可以找到更好的最小值

    注意,您可以只使用一对名称和时间(Pair<String, Integer>);不需要索引

    在这里,它可能过于高级和间接,但它既非常有表达力,又非常干净(使用步骤而不需要局部变量)

  2. # 2 楼答案

    可以将变量设置为元素的索引,而不只是获取该元素的值

    public static void lowesttime(String[] names, int[] times) {
        int lowest;
        int lowestIndex = 0;
    
        lowest = times[0];
        for (int i = 1; i < times.length; i++) {
            if (times[i] < lowest) {
                lowest = times[i];
                lowestIndex = i;
            }
        }
        System.out.println(lowest);
        System.out.println(lowestIndex);
    
        // to access arrays names[?], times[?}
        // System.out.println(names[lowest] + ": " + times[lowest]);
    
    }
    
  3. # 3 楼答案

    如果您已经知道最低值,可以使用:

    java.util.Arrays.asList(theArray).indexOf(lowestValue)