[leetcode] 73. Set Matrix Zeroes

Given am 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?

这道题是修改矩阵中数字0所在的行列数据为0,题目难度为Medium。

题目的关键在于in-place,所谓in-place,即要求空间复杂度为O(1),一般来说会使用已有的变量来存储中间变量和状态。

根据题目要求,需要统计所有的行和列是否有0存在,如果有0该行和该列即可全部修改为0,一般情况下需要O(m+n)的空间来存储状态。既然题目要求in-place,这里O(m+n)的空间就需要用原来矩阵的空间来存储,很自然我们会想到用一行和一列来记录下这些状态。这里我们用第一行来记录所有列中是否有0存在,用第一列来记录所有行中是否有0存在,同时问题来了,matrix[0][0]只能记录第一行或第一列的状态,因而我们需要额外的变量来记录另一个状态。代码中用firstRowHasZero来记录第一行是否有0,这样问题就迎刃而解了。具体代码:

class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        if(matrix.empty()) return;
        bool firstRowHasZero = false;
        int row = matrix.size();
        int col = matrix[0].size();
        
        for(int i=0; i<col; ++i) {
            if(!matrix[0][i]) {
                firstRowHasZero = true;
                break;
            }
        }
        
        for(int i=1; i<row; ++i) {
            for(int j=0; j<col; ++j) {
                if(!matrix[i][j]) {
                    matrix[0][j] = 0;
                    matrix[i][0] = 0;
                }
            }
        }
        
        for(int i=1; i<row; ++i) {
            for(int j=col-1; j>=0; --j) {
                if(!matrix[i][0] || !matrix[0][j]) {
                    matrix[i][j] = 0;
                }
            }
        }
        
        if(firstRowHasZero) {
            for(int i=0; i<col; ++i) {
                matrix[0][i] = 0;
            }
        }
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值