leetcode 73. Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

Follow up:

Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?

思路很简单,就是先把matrix过一遍,哪一行哪一列有0,用bealoon记录一下。

然后第二次遍历,把有bealoon记录为true的行和列都变成0;

code

public class SetMatrixZero {
    public void setZero(int[][] Matrix){
        boolean[] row = new boolean[Matrix.length];
        boolean[] col = 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;
                    col[j] = true;
                }
            }
        }
        
        for(int i = 0; i < Matrix.length; i++){
            for(int j = 0; j < Matrix[0].length; j++){
                if(row[i] || col[j]){
                    Matrix[i][j] =0;
                }
            }
        }
        }
}

Follow up: 关于extra空间的占用,思路就是先把第一行和第一列遍历一次,记录是否有0,如果有0,用bealoon记录为true.

然后在matrix的第二行和第二列开始遍历,遇到0,就在对应的第一行和第一列做记录为0。

最后把第列从第2个开始遍历,(一开始从0开始遍历,没通过,后来没通过,才发现问题。)行也是如此。

最后判断原始的第一行和第一列是不是有记录false的,如果有,就把相应的行和列变成0

code:

public class SetMatrixZero {
    public void setZero(int[][] Matrix){
        boolean row = false;
        boolean col = false;
        for(int i = 0; i < Matrix.length; i++){
            if(Matrix[i][0] == 0)
                row = true;
        }
        for(int j = 0; j < Matrix[0].length; j++){
            if(Matrix[0][j] == 0)
                col = true;
        }
        
        for(int i = 1; i < Matrix.length; i++){
            for(int j = 1; j < Matrix[0].length; j++){
                if(Matrix[i][j] == 0){
                    Matrix[i][0] = 0;
                    Matrix[0][j] = 0;
                }
            }
        }
        
        for(int i = 1; i < Matrix.length; i++){
            if(Matrix[i][0] == 0){
                for(int j = 1; j < Matrix[0].length; j++){
                    Matrix[i][j] = 0;
                }
            }
        }
        
        for(int i = 1; i < Matrix[0].length; i++){
            if(Matrix[0][i] == 0){
                for(int j = 1; j < Matrix.length; j++){
                    Matrix[j][i] = 0;
                }
            }
        }
        
        if(row == true){
            for(int i = 0; i < Matrix.length; i++){
                Matrix[i][0] = 0;
            }
        }
        
        if(col == true){
            for(int i = 0; i < Matrix[0].length; i++){
                Matrix[0][i] = 0;
            }
        }    
    }
}
原文地址:https://www.cnblogs.com/hewx/p/5123137.html