【LeetCode热题100】--73.矩阵置零

73.矩阵置零

【LeetCode热题100】--73.矩阵置零_第1张图片

使用标记数组:

使用两个标记数组分别记录每一行和每一列是否有零出现

先遍历一次数组,如果某个元素为0,则将该元素所在的行和列所对应的标记数组的位置为true,最后再遍历该数组,用标记数组更新原数即可

class Solution {
    public void setZeroes(int[][] matrix) {
        int m = matrix.length;  //矩阵的行数
        int n = matrix[0].length;  //矩阵的列数
        boolean[] row = new boolean[m];
        boolean[] col = new boolean[n];
        for(int i = 0;i<m;i++){
            for(int j = 0; j<n ;j++){
                if(matrix[i][j] == 0){
                    row[i] = col[j] =true;
                }
            }
        }
        for(int i = 0;i<m;i++){
            for(int j = 0;j<n;j++){
                if(row[i] || col[j]){
                    matrix[i][j] = 0;
                }
            }
        }
    }
}

你可能感兴趣的:(LeetCode,leetcode,算法)