[英]How to find all occurences of the highest number in a list?
基本上,如果我有一個ArrayList<Integer>
包含<0, 1, 5, 5, 4, 2>
,我需要為索引創建一個單獨的<2, 3>
ArrayList
。
我了解如何獲取最大數字的第一次出現的索引,但我不知道如何同時獲取所有這些索引。
我原本是在想:
int highest = 0;
for (int b = 0; b < arrlst.size(); b++) {
int p = arrlst.get(b);
if (highest <= p) {
highest = p;
highestindex.add(b);
}
}
但后來我意識到這會自動添加第一個,以及任何高於當前最大值的,即使它們不是整體最大值。
然后我想到將highestindex.add(...)
部分放在循環之外,但它只會添加最后一個索引,而不是全部。
我會 go 添加和清除List<Integer>
:
public ArrayList<Integer> getIndexesOfHighestNum(List<Integer> list) {
List<Integer> indexes = new ArrayList<Integer>();
int highest = Integer.MIN_VALUE;
for (int i = 0; i < list.size(); i++) {
int value = list.get(i);
if (value > highest) {
indexes.clear();
indexes.add(i);
highest = value;
} else if (value == highest)
indexes.add(i);
}
return indexes;
}
您可以使用 stream 來做到這一點,
int max = intArr.stream().reduce(Integer::max).get();
IntStream.range(0, intArr.size()).boxed()
.filter(i -> max == intArr.get(i))
.collect(Collectors.toList());
您可以先獲取最大數量,然后保存具有此值的元素的索引,如下所示:
private static List<Integer> getMaxIndices(int[] list){
int max = list[0];
for(int i = 1; i < list.length; i++)
if(max < list[i])
max = list[i];
List<Integer> res = new ArrayList<>();
for(int i = 0; i < list.length; i++)
if(list[i] == max)
res.add(i);
return res;
}
為了簡化代碼,我們可以使用Collections#max
來獲取最大值。
為了更好地表達我們的意圖(過濾索引最大值),我們可以使用IntStream
代替 for 循環。
public static List<Integer> getMultipleMaxIndex(final List<Integer> from) {
if (from.isEmpty()) {
return Collections.emptyList();
}
final Integer max = Collections.max(from);
IntStream indexes = IntStream.range(0, from.size() - 1);
return indexes.filter(index -> from.get(index).equals(max)).boxed().collect(Collectors.toList());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.