【问题标题】:How to return max in ArrayList when two values are tied for max?当两个值绑定为最大值时,如何在 ArrayList 中返回最大值?
【发布时间】:2017-08-31 17:37:56
【问题描述】:

到目前为止,我有这个方法,它应该找到一个 ArrayList 的最大年龄。但是,在我的数据中,我有两个值并列在 58 处,用于关节最大值。如何从这个循环中获得第二个 58?前 58 个的索引是 1,但我需要的索引是 4。我不能硬编码。

public static int maxAge (ArrayList<Integer> ages) {
        int hold = 0;
        int max = 0;
        for (int i = 0; i < ages.size(); i++) {
            if (max < ages.get(i)) {
                max = ages.get(i);
                hold = i;
            }
            else i++;       
        }
        return hold;
    }

【问题讨论】:

  • 您要返回两个结果,还是只返回最后一个?
  • 如果等式如 if (max
  • 不相关: 删除 else i++;。它会导致不正确的结果,因为它会跳过元素。

标签: java loops arraylist methods


【解决方案1】:

您可以简单地将您的条件更改为:

if (max &lt;= ages.get(i))

【讨论】:

    【解决方案2】:

    这取决于你为什么想要其他 58 个。如果你想返回最新的匹配,你可以向后循环。

    【讨论】:

      【解决方案3】:

      下面的代码将使您能够返回与列表最大值相关的所有索引。但是你必须在 Java 8 上运行它,因为它使用 Lambda 表达式。

      public static ArrayList<Integer> maxAge (ArrayList<Integer> ages ) {
              int max = 0;
              ArrayList<Integer> maxIndexes = new ArrayList<Integer>() ;
              for (int i = 0; i < ages.size(); i++) {
                  if (max <= ages.get(i)) {
                      final int finalMax = max ;
                      final int finalIndex = i ;
                      maxIndexes.removeIf((elt)-> finalMax < ages.get(finalIndex)) ;
                      maxIndexes.add(i) ;
                      max = ages.get(i) ;
                  }               
              }
              return maxIndexes ;
          }
      

      【讨论】:

        【解决方案4】:

        我知道,很丑。但我会尝试编写一个功能版本。

        Optional<Integer> max = ages.stream()
                                    .max(Integer::compare);
        if (max.isPresent()) {
          return IntStream.range(0, ages.size())
                          .mapToObj(pos -> {
                            return new int[] {pos, ages.get(pos)};
                          })
                          .filter(pair -> pair[1] == max.get())
                          .collect(Collectors.toCollection(LinkedList::new))
                          .getLast()[0];
        } else
          return 0;
        

        【讨论】:

          【解决方案5】:

          有多种方法可以更改条件以适合您的描述。试试这个:

          public static int maxAge (ArrayList<Integer> ages) {
              int hold = 0;
              int max = 0;
              for (int i = 0; i < ages.size(); i++) {
                  if (max < ages.get(i) || max == ages.get(i) {
                      max = ages.get(i);
                      hold = i;
                  }
                  else i++;       
              }
              return hold;
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2010-12-07
            • 2015-09-26
            • 2011-03-27
            • 2020-07-03
            • 2016-01-05
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多