【问题标题】:How to return first max value in a Java ArrayList如何在 Java ArrayList 中返回第一个最大值
【发布时间】:2017-12-31 05:12:28
【问题描述】:

我正在尝试返回ArrayList<Integer> 的最大值的第一个索引。下面的代码找到第二个最大值而不是第一个最大值。如何返回循环遇到的第一个最大值?

public int findIndexOfMax() {
    int maxIndex = 0;
    for (int k = 0; k < myFreqs.size(); k++) {
        if (myFreqs.get(k) > maxIndex) {
            maxIndex = myFreqs.get(k);
        }
    }
    return maxIndex;
}

返回的是 'test. 3'。但它应该是字母“a”的第一个最大值,即 3。

Number of unique words: 7
1   this
1   is
3   a
3   test.
1   yes
1   test
1   of
The word that occurs most often and its count are: test. 3

【问题讨论】:

  • 您将什么定义为循环中的第一个最大值?
  • 您只需为此使用HashMap,如here所示。

标签: java for-loop arraylist integer max


【解决方案1】:

您似乎忘记在比较中访问maxIndex 处的元素。您将 index 设置为 if 中元素的 value(而不是 index)。我想你想要,

public int findIndexOfMax() {
    int maxIndex = 0;
    for (int k = 1; k < myFreqs.size(); k++) {
        if (myFreqs.get(k) > myFreqs.get(maxIndex)) {
            maxIndex = k;
        }
    }
    return maxIndex;
}

【讨论】:

    【解决方案2】:

    我认为您使用左侧的整数作为右侧字符串的索引,当您第二次使用 3 作为索引时,它会将值“a”与“test”重叠。

    【讨论】:

      猜你喜欢
      • 2017-08-31
      • 1970-01-01
      • 1970-01-01
      • 2022-07-13
      • 2023-03-10
      • 1970-01-01
      • 2014-11-28
      • 1970-01-01
      • 2021-07-06
      相关资源
      最近更新 更多