【问题标题】:How to find all occurences of the highest number in a list?如何在列表中查找所有出现的最高数字?
【发布时间】:2020-07-24 22:31:28
【问题描述】:

基本上,如果我有一个包含<0, 1, 5, 5, 4, 2>ArrayList<Integer>,我需要为索引创建一个单独的ArrayList<2, 3>

我知道如何获取最大数的第一次出现的索引,但我不知道如何同时获取所有这些。

我原本在想:

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(...) 部分放在循环之外,但它只会添加最后一个索引,而不是全部。

【问题讨论】:

  • 顺便说一句,忽略那个 v,它是一个 p,对不起
  • 你可以随时编辑你的帖子:)

标签: java loops arraylist


【解决方案1】:

我会去添加和清除List&lt;Integer&gt;

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

【讨论】:

  • 是否整数.MIN_VALUE;让最高值自动从最低值开始?
  • 是的,它是整数可以具有的最小值。这保证了如果所有值都是负数,算法仍然会选择最高的值。
【解决方案2】:

你可以用流来做到这一点,

int max = intArr.stream().reduce(Integer::max).get();
IntStream.range(0, intArr.size()).boxed()
        .filter(i -> max == intArr.get(i))
        .collect(Collectors.toList());

【讨论】:

    【解决方案3】:

    您可以先获取最大数量,然后将具有该值的元素的索引保存如下:

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

    【讨论】:

      【解决方案4】:

      为了简化代码,我们可以使用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());
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-11
        • 2012-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多