自学内容网 自学内容网

JAVA-矩阵置零

给定一个 m x n 的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。
在这里插入图片描述
思路:
找到0的位置,把0出现的数组的其他值夜置为0
需要额外空间方法:
1、定义两个布尔数组标记二维数组中行和列0出现的位置,标记在布尔数组中。
2、在遍历二维数组,把行和列0出现的位置都重置为0.

class Solution {
    public void setZeroes(int[][] matrix) {
        /** 如果数组中包含0,就把这个里面的数都设置为0
        关键在于如何把0标注以及如何重置0
         */

       int rows = matrix.length;
       int cols = matrix[0].length;
       boolean [] rowsZero = new boolean[rows];
       boolean [] colsZero = new boolean[cols];

       for (int i = 0; i < rows; i++){
        for (int j = 0; j < cols; j ++) {
            if(matrix[i][j] == 0) {
                rowsZero[i] = true;
                colsZero[j] = true;
            }
        }
       }

       for (int i = 0; i < rows; i++){
         for (int j = 0; j < cols; j ++) {
            if(rowsZero[i] || colsZero[j]){
                matrix[i][j] = 0;
            }
         }
        }

    }
}

原文地址:https://blog.csdn.net/weixin_44591656/article/details/140050923

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!