LeetCode —— Set Matrix Zeroes

链接:http://leetcode.com/onlinejudge#question_73

原题:

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?

思路:这道题目关键是要求constant space solution,所以要转变记录状态的方法。

我是利用相邻两行做状体记录的。

1)判断下一行是否有0,如果有的话,那么处理改行时候,要把所有非0值置为0;

2)把当前行有0的列,在下一行对应的列那个值也置为0。

3)最后处理最后一行,把有0的列,都全部置为0

时间为O(m*n), 空间复杂度为O(1)


代码:

class Solution {
public:
    void setZeroes(vector<vector<int> > &matrix) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (matrix.size() == 0)
            return;
            
        int rows = matrix.size();
        int cols = matrix[0].size();
        
        bool nextFlag = existZeroInRow(matrix, 0);
        int i = 0;
        for ( ; i<rows-1; i++) {
            bool curFlag = nextFlag;
            nextFlag = existZeroInRow(matrix, i+1);
            for (int j=0; j<cols; j++) {
                if (matrix[i][j] != 0 && curFlag) {
                    matrix[i][j] = 0;
                } else if (matrix[i][j] == 0) {
                    matrix[i+1][j] = 0;
                }
            }
        }
        
        //process the last raw
        for (int j=0; j<cols; j++) {
            if (matrix[i][j] != 0 && nextFlag) {
                    matrix[i][j] = 0;
            } else if (matrix[i][j] == 0) {
                for (int n=0; n<=i; n++)
                    matrix[n][j] = 0;
            }
        }
    }

private:
    bool existZeroInRow(const vector<vector<int> > &matrix, int row) {
        int cols = matrix[row].size();
        for (int i=0; i<cols; i++) {
            if (matrix[row][i] == 0)
                return true;
        }
        
        return false;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值