在Java中打印并计算二维数组中的最大值数量

3

我有一个Java的二维数组,需要查找其中的最大值,并打印出它在数组中出现的次数。

我尝试了以下方法,但没有成功。

        int[][] rand = new int[][]{
                {1, 80, 3, 4, 5},
                {13, 199, 80, 8},
                {12, 22, 80, 190}
        };

        int max = rand[0][0];
        int count = 0;
        for (int i = 0; i < rand.length; i++){
            for (int ii = 0; ii < rand[i].length; ii++) {
                if (rand[i][ii] > max) {
                    max = rand[i][ii];
                    count++;
                }

            }
        }
        System.out.println(max + " " + count);


你走在正确的道路上,但每次找到一个更大的值时,你需要重置计数。这意味着你还需要一个if语句,如果该值等于最大值,则增加计数。 - David Brossard
所以在你的代码中,当它说 count++ 时,将 count 设为 1,然后添加一个 else if 语句来在值等于最大值时增加 count。 - David Brossard
1
此外,您可能需要处理空数组。在空数组上执行语句rand[0][0]将引发OutOfBoundsException异常。 - pxcv7r
2个回答

2

你没有正确处理计数:

int max = rand[0][0];
int count = 0
for (int i = 0; i < rand.length; i++){
    for (int ii = 0; ii < rand[i].length; ii++) {
        if (rand[i][ii] > max) {
            max = rand[i][ii];
            count = 1; // a new maximum's first occurrence
        } else if (rand[i][ii] == max) {
            count++; // another occurrence of the current maximum
        }
    }
}
System.out.println(max + " " + count);
  • 当你发现一个新的最大值时,你应该将count重置为1。

  • 你应该检查当前元素是否等于当前最大值,如果是,则增加count

输出:

199 1

编辑:

修复了第一个元素是最大值的情况。原来,由于循环会重新访问第一个元素,所以我们不想重复计数,如果它是最大值,则应该将count初始化为0


2
这是错误的解决方案。请尝试以下代码: int[][] rand = new int[][]{ {200, 80, 199, 199, 5}, {13, 199, 80, 8}, {12, 22, 80, 200} }; - A.Alexander
1
@A.Alexander 哦,你说得对。count应该在所有操作之后初始化为0。 - Eran
1
@Eran - 我们几乎同时发布了我们的答案,但当我看到你的答案时,我甚至没有意识到你犯了那个错误,为了向像您这样伟大的人致敬,我删除了我的答案,没有这个错误。 - Arvind Kumar Avinash

0

你可以使用流:

    int max = Arrays.stream(rand)
            .mapToInt(row -> Arrays.stream(row).max().getAsInt())
            .max().getAsInt();

    int count = Arrays.stream(rand)
            .mapToInt(row -> (int) Arrays.stream(row).filter(i-> i==max).count())
            .reduce(Integer::sum).getAsInt();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接