亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 int 數組中,如何返回對應于最低值的索引?

在 int 數組中,如何返回對應于最低值的索引?

汪汪一只貓 2023-08-09 16:10:12
我已經設法用“最低”變量找到數組中的最低值,但我正在尋找與數組中最低值相對應的索引。有任何想法嗎?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 回答

?
慕娘9325324

TA貢獻1783條經驗 獲得超4個贊

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());

}

我想使用 Stream 來展示:

  • IntStream.range(0, N)將給出 0, 1, 2, ..., N-1 的流。指數。

  • mapToObj轉換為 a Stream<Pair<Integer, Integer>>,其中對鍵是索引,對值是times[index]。

  • reduce將以初始對(-1,Integer.MAX_VALUE)作為結果開始,然后對于流中的每一對是否可以找到更好的最小值。

請注意,您可以只使用一對名稱和時間 ( Pair<String, Integer>);不需要索引。

這里可能過于高級和具體,但它非常具有表現力干凈(使用步驟而不需要局部變量)。


查看完整回答
反對 回復 2023-08-09
?
蝴蝶不菲

TA貢獻1810條經驗 獲得超4個贊

您可以將變量設置為元素的索引,而不僅僅是獲取該元素的值;


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


}


查看完整回答
反對 回復 2023-08-09
?
呼喚遠方

TA貢獻1856條經驗 獲得超11個贊

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

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


查看完整回答
反對 回復 2023-08-09
  • 3 回答
  • 0 關注
  • 149 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號