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;
            }
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容