计算二维整数数组最小值的程序

我正在尝试创建一个程序,它计算二维数组中每个维度的最小值。所以对于前。如果我有一个数组:


int[][] test = {{1,2,3},{2,3,4},{4,5,6}}

程序将显示: [1,2,4] - 每个维度的最小值。为此,我创建了一个名为 minimum 的方法,它看起来像这样


static int[] minimum(int[][] arr) {

        int[] result = new int [arr.length];

        for (int i = 0; i < arr.length; i++) {

            for(int j = 0; j < arr[i].length; j++) {

                int  min = arr[i][0];

                if(arr[i][j] < min) {

                    min = arr [i][j];

                    result [i] = min;

                } else{


                }

            }

        }

        return result;

    }

但是当我在主程序中调用此方法时,使用示例数组


public static void main(String[] args) {

            int[][] arr = {{1,2,3,},{3,4,5},{6,6,6}};

        System.out.println(Arrays.toString(minimum(arr)));



    }

程序显示 [0,0,0,]。您知道问题出在哪里以及如何解决吗?


有只小跳蛙
浏览 132回答 2
2回答

慕的地8271018

问题是如果数组中的第一个元素是 min,它永远不会被记录到结果数组中。尝试:static int[] minimum(int[][] arr) {&nbsp; &nbsp; int[] result = new int[arr.length];&nbsp; &nbsp; for (int i = 0; i < arr.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; result[i] = arr[i][0];&nbsp; &nbsp; &nbsp; &nbsp; for (int j = 1; j < arr[i].length; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (arr[i][j] < result[i]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result[i] = arr[i][j];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return result;}请注意,上述函数的输入矩阵中每行至少需要一个元素;Integer.MIN_VALUE如果您愿意,可以添加条件或用于处理空行。

噜噜哒

这应该有效。您每次都将 min 重置为第一个元素。因此,您基本上是在比较是否有任何值小于第一个值。&nbsp; &nbsp; static int[] minimum(int[][] arr){&nbsp; &nbsp; &nbsp; &nbsp; int[] result = new int [arr.length];&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < arr.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result[i] = Integer.MAX_VALUE;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(int j = 0; j < arr[i].length; j++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(arr[i][j] < result[i]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result [i] = arr[i][j];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return result;&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java