gpt4 book ai didi

java - ArrayList 中最大项的索引

转载 作者:行者123 更新时间:2023-11-29 04:08:36 26 4
gpt4 key购买 nike

让我们以这个 ArrayList 为例 [1, 3, 8, 9, 5, 7, 9]。

我正在努力获取列表中最大项目的索引,如果列表多次包含该项目,则每次都返回不同的索引。

我们可以看到最大的项目 9 在索引 3 和索引 6 处。

这是我到目前为止一直在做的事情:

public static int getIndexOfLargest( List<Integer> list ){
List<Integer> index = new ArrayList();
if ( list == null || list.size() == 0 ) return -1; // null or empty
Integer i=0, maxIndex=-1, max=null;
for (Integer x : list) {
if ((x!=null) && ((max==null) || (x>max))) {
max = x;
maxIndex = i;
}
i++;
}
return maxIndex;
}

上面的代码只输出索引 3。如何更新代码以获取索引列表 [3, 6]

最佳答案

试试这个:

public static List<Integer> getIndexOfLargest(List<Integer> list) {
List<Integer> indicesOfLargest = new ArrayList();
if (list == null || list.size() == 0)
return indicesOfLargest; // null or empty
Integer i = 0, max = null;
for (Integer x : list) {
if (x != null) {
if (max == null || x > max) {
indicesOfLargest.clear();
max = x;
indicesOfLargest.add(i);
} else if (x == max) {
indicesOfLargest.add(i);
}
i++;
}
}
return indicesOfLargest;
}

关于java - ArrayList 中最大项的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56619172/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com