【集合】LeetCode 73. 矩阵置零

题目链接

73. 矩阵置零

思路1

遍历矩阵,分别使用集合 rowcolumn 记录值为0的行和列。最后将 rowcolumn所记录的行和列置为零。

空间复杂度: \(O(m + n)\)

代码1

class Solution {
    public void setZeroes(int[][] matrix) {
        Set<Integer> row = new HashSet<>();
        Set<Integer> column =  new HashSet<>();

        for(int i = 0; i < matrix.length; i++){
            for(int j = 0; j < matrix[i].length; j++){
                if(matrix[i][j] == 0){
                    row.add(i);
                    column.add(j);
                }
            }
        }

        for(int i : row){
            Arrays.fill(matrix[i], 0);
        }

        for(int j : column){
            for(int i = 0; i < matrix.length; i++){
                matrix[i][j] = 0;
            }
        }
    }
}

思路2

该题还可以让矩阵的首行和首列成为标记变量,如果该行或者该列有0出现,则将行首或列首元素置为0。为了区首行和首列是否本来就有0,使用两个 boolean 类型变量分别记录首行和首列的初始状态。如果有0则为 true

空间复杂度: \(O(1)\)

代码2

class Solution{
    public void setZeroes(int[][] matrix){
        boolean firstRowHasZero = false;
        boolean fistColHasZero = false;

        for(int i = 0; i < matrix.length; i++){
            for(int j = 0; j < matrix[0].length; j++){
                if(matrix[i][j] == 0){
                    if(i == 0){
                        firstRowHasZero = true;
                    }
                    if(j == 0){
                        fistColHasZero = true;
                    }
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }

        for(int i = 1; i < matrix.length; i++){
            for(int j = 1; j < matrix[0].length; j++){
                if(matrix[i][0] == 0 || matrix[0][j] == 0){
                    matrix[i][j] = 0;
                }
            }
        }

        if(firstRowHasZero){
            for(int i = 0; i < matrix[0].length; i++){
                matrix[0][i] = 0;
            }
        }
        if(fistColHasZero){
            for(int i = 0; i < matrix.length; i++){
                matrix[i][0] = 0;
            }
        }
    }
}
posted @ 2023-01-06 11:25  Frodo1124  阅读(29)  评论(0编辑  收藏  举报