73. Set Matrix Zeroes

Description

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?

Solution

Iteration

这道题目需要先遍历一次查找0,利用额外空间去保存某行或某列是否含有0,再遍历一次将元素修改成0。这样子呢是O(m + n)的空间复杂度。
细细想来可以利用matrix的第零行和第零列作为标记位,这样额外只需要两个变量用于标识第零行和第零列是否有零即可。注意最后修改值的时候,标记位需要最后改才行,否则会影响其他元素。

class Solution {
    public void setZeroes(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return;
        }
        
        int rows = matrix.length;
        int cols = matrix[0].length;
        boolean firstRowHasZero = false;
        boolean firstColHasZero = false;
        
        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                if (i == 0) {
                    firstRowHasZero = firstRowHasZero || matrix[i][j] == 0;
                }
                
                if (j == 0) {
                    firstColHasZero = firstColHasZero || matrix[i][j] == 0;
                }
                
                if (i > 0 && j > 0 && matrix[i][j] == 0) {
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }
        
        for (int i = 1; i < rows; ++i) {
            for (int j = 1; j < cols; ++j) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0) {
                    matrix[i][j] = 0;
                }
            }
        }
        
        if (firstRowHasZero) {
            for (int i = 0; i < cols; ++i) {
                matrix[0][i] = 0;
            }
        }
        
        if (firstColHasZero) {
            for (int i = 0; i < rows; ++i) {
                matrix[i][0] = 0;
            }
        }
    }
}

你可能感兴趣的:(73. Set Matrix Zeroes)