HanLue
Everything is Object

问题:

 

看到题目第一想法是遍历整个数组,找到值为0的项置同行,同列的值为0即可,但这样做会导致整个数组值为0。

评论区老哥DonYong解答让我恍然大悟,既然要置整行整列的项都为0,那就无需将具体为0的值的位置求出,只需要知道哪一行哪一列为0即可。 

class Solution {
    public void setZeroes(int[][] matrix) {
        boolean[] row = new boolean[matrix.length];
        boolean[] column = new boolean[matrix[0].length];
        for(int i = 0;i<matrix.length;i++) {
            for(int j = 0;j<matrix[0].length;j++) {
                if(matrix[i][j] == 0) {
                    row[i] = true;
                    column[j] = true;
                }
            }
        }
        for(int i=0;i<matrix.length;i++) {
            for(int j=0;j<matrix[0].length;j++) {
                if(row[i]||column[j]) {
                    matrix[i][j] = 0;
                }
            }
        }
    }
}

 

定义boolean型数组row,column。遍历二维数组,将值为0的项的行和列赋值给布尔数组。再次遍历数组,只要行值或列值有一个为true,那么就将具体值matrix[i][j]置0;

 

posted on 2021-05-21 16:51  HanLue  阅读(163)  评论(1)    收藏  举报