LeetCode 79 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?

分析:

1,最直观的想法就是另外开辟一个标记矩阵来标记0位置;

2,进一步的想法是开辟两个数组,一个标记行,一个标记列;

题目要求原地,可以利用第一行和第一列作为标记数组来标记行和列。

这样带来的麻烦就是我们必须先检查第一行和第一列是否含有0元素,最后还要恢复第一行和第一列。

public class Solution {
    public void setZeroes(int[][] matrix) {
        //参数检查
        if(matrix==null || matrix.length==0 || matrix[0].length==0)
            return;
        int row = matrix.length;
        int col = matrix[0].length;
        boolean zeroFirstRow = false;
        boolean zeroFirstCol = false;
        //检查第一行和第一列是否有0元素
        for(int i=0; i<row; i++){
            if(matrix[i][0] == 0)
                zeroFirstCol = true;
        }
        for(int i=0; i<col; i++){
            if(matrix[0][i] == 0)
                zeroFirstRow = true;
        }
        //以第一行和第一列作为标记数组
        for(int i=1; i<row; i++){
            for(int j=1; j<col; j++){
                if(matrix[i][j]==0){
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }
        //根据标记数组对矩阵进行重新赋值
        for(int i=1; i<row; i++){
            for(int j=1; j<col; j++){
                if(matrix[i][0]==0 || matrix[0][j]==0)
                    matrix[i][j] = 0;
            }
        }
        //对第一行和第一列进行重新赋值
        if(zeroFirstRow == true){
            for(int i=0; i<col; i++)
                matrix[0][i] = 0;
        }
        if(zeroFirstCol == true){
            for(int i=0; i<row; i++)
                matrix[i][0] = 0;
        }
    }
}



你可能感兴趣的:(LeetCode,set,Matrix,zeroes)