在 Java 2D 数组中查找最小值和最大值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38286212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:11:02  来源:igfitidea点击:

Finding minimum and maximum in Java 2D array

javaarraysloopsmaxmin

提问by Fancierwhale

I have been trying to figure this out for a while and need some help. I need to find the min/max values and print them out for a multidimensional array. Here are the two ways that I have tried.

我一直在努力解决这个问题,需要一些帮助。我需要找到最小/最大值并将它们打印出来用于多维数组。这是我尝试过的两种方法。

import java.util.*;

class MinMax {
    public static void main(String[] args) {
        int[][] data = {{3, 2, 5},
                {1, 4, 4, 8, 13},
                {9, 1, 0, 2},
                {0, 2, 6, 3, -1, -8}};
        Arrays.sort(data);
        System.out.println("Minimum = " + data[0]);
        System.out.println("Maximum = " + data[data.length - 1]);
    }
}

This version complies but doesn't run.

此版本符合但不运行。

import java.util.*;

class MinMax {
    public static void main(String[] args) {
        int[][] data = {{3, 2, 5},
                {1, 4, 4, 8, 13},
                {9, 1, 0, 2},
                {0, 2, 6, 3, -1, -8}};

    public static int getMaxValue(int[] numbers) {
        int maxValue = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > maxValue) {
                maxValue = numbers[i];
            }
            return maxValue;
            {
                public static int getMinValue (int[] numbers) {
                    int minValue = numbers[0];
                    for (int i = 1; i < numbers.length; i++) {
                        if (numbers[i] < minValue) {
                            minValue = numbers[i];
                        }
                    }
                return minValue;
            }

This version just throws me a bunch of errors in compiling. Any help is greatly appreciated.

这个版本只是在编译时给我带来了一堆错误。任何帮助是极大的赞赏。

采纳答案by Pavel S.

Ok, I've kinda fixed your code. Actually your mistake was that you have not been traversing all the cells of your multidimensional array.

好的,我已经修复了你的代码。实际上你的错误是你没有遍历多维数组的所有单元格。

So, I've added additional loop into getMinValue/getMinValue methods and fixed array elements addressing.

因此,我在 getMinValue/getMinValue 方法和固定数组元素寻址中添加了额外的循环。

import java.util.*;

class MinMax {
    public static void main(String[] args) {
        int[][] data = {
                {3, 2, 5},
                {1, 4, 4, 8, 13},
                {9, 1, 0, 2},
                {0, 2, 6, 3, -1, -8}
        };
        System.out.println(getMaxValue(data));
        System.out.println(getMinValue(data));
    }


    public static int getMaxValue(int[][] numbers) {
        int maxValue = numbers[0][0];
        for (int j = 0; j < numbers.length; j++) {
            for (int i = 0; i < numbers[j].length; i++) {
                if (numbers[j][i] > maxValue) {
                    maxValue = numbers[j][i];
                }
            }
        }
        return maxValue;
    }

    public static int getMinValue(int[][] numbers) {
        int minValue = numbers[0][0];
        for (int j = 0; j < numbers.length; j++) {
            for (int i = 0; i < numbers[j].length; i++) {
                if (numbers[j][i] < minValue ) {
                    minValue = numbers[j][i];
                }
            }
        }
        return minValue ;
    }
}

回答by Alexandar Petrov

I have a more fun solution using Java 8 :)

我有一个使用 Java 8 的更有趣的解决方案 :)

IntSummaryStatistics stats = Arrays.stream(data).flatMapToInt(Arrays::stream).collect(Collectors.summarizingInt(Integer::intValue));
int max = stats.getMax();
int min = stats.getMin();

It's a different solution than yours, obviously. But it does the same thing. To begin with, we convert the 2D array into a Streamof ints. In order to do this first we need to call flatMapToInt. We do this to stream all the elements in the array in a flat way. Imagine if we just start using a single index to iterate over the whole 2D array. It's something like that. Once we have converted the array into a stream, we will use IntSummaryStatistics in order to reuse the same stream for both min and max.

显然,这与您的解决方案不同。但它做同样的事情。首先,我们将二维数组转换为 a Streamof ints。为了首先做到这一点,我们需要调用flatMapToInt. 我们这样做是为了以扁平的方式流式传输数组中的所有元素。想象一下,如果我们只是开始使用单个索引来遍历整个 2D 数组。就是这样。一旦我们将数组转换为流,我们将使用 IntSummaryStatistics 以便为 min 和 max 重用相同的流。

回答by MasterBlaster

Your problem is:You are sorting the array of intarrays instead of sorting each individual intin each intarray.

您的问题是:您正在对数组int数组进行排序,而不是对int每个int数组中的每个人进行排序。

To solve this:Loop through each intarray in the array of intarrays.

解决这个问题:循环遍历int数组数组中的每个数组int

Instructionsfor finding the maximum and minimum of a 2D intarray using Arrays.sort():

使用以下命令查找二维int数组的最大值和最小值的说明Arrays.sort()

  1. Declare a 2D intarray to sort called data.
  2. Declare two ints, one to hold the maximum value, the other the minimum value.
    • The initial value of the maximum should be Integer.MIN_VALUEand the initial value of the minimum should be Integer.MAX_VALUEto make sure that negative values are handled.
  3. Loop through datafrom 0to data.length:
    1. Sort data[i]
    2. Check if the first value of data[i]is less than the minimum and change it if it is.
    3. Check if the last value of data[i]is greater than the maximum and change it if it is.
  4. Output your result.
  1. 声明一个二维int数组进行排序,称为data.
  2. 声明两个ints,一个保存最大值,另一个保存最小值。
    • 最大值Integer.MIN_VALUE的初始值应该是Integer.MAX_VALUE,最小值的初始值应该是确保负值被处理。
  3. 循环data0data.length
    1. 种类 data[i]
    2. 检查的第一个值data[i]是否小于最小值,如果是则更改它。
    3. 检查的最后一个值data[i]是否大于最大值,如果是则更改它。
  4. 输出你的结果。

Example:

例子:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[][] data = {{3, 2, 5},
            {1, 4, 4, 8, 13},
            {9, 1, 0, 2},
            {0, 2, 6, 3, -1, -8} };

        int maximum = Integer.MIN_VALUE;
        int minimum = Integer.MAX_VALUE;

        for(int i = 0; i < data.length; i++) {
            Arrays.sort(data[i]);

            if(data[i][0] < minimum) minimum = data[i][0];
            if(data[i][data[i].length - 1] > maximum) maximum = data[i][data[i].length - 1];
        }

        System.out.println("Minimum = " + maximum);  
        System.out.println("Maximum = " + minimum); 
    }
}

回答by md mahabub

package array;

包数组;

public class Max_number {

公共类 Max_number {

// 2 5 7 9
// 3 6 8 1

public static void main (String []arg) {

    int a[][] = {{2,5,7,9},{3,6,8,1}};
    int max=a[0][0];
    for (int i=0; i<2; i++) //row
    {
        for (int j=0; j<4; j++) //coloum
        {
            if(a[i][j]>max)
            {
                max=a[i][j];
        }

    }

}
    System.out.println("maximum number is"+max);
}

}

}