LeetCode 之 Set Matrix Zeroes — C++实现

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?

给定 m×n的矩阵,如果存在 0,则将其所在的整个行和列都设置为0,要在原地操作。

分析:
法1:重新分配一个矩阵来记录矩阵中0的位置,则空间复杂度为 O(mn)。
法2:分配两个向量来记录行和列中是否有0,则空间复制度为 O(m+n)。
法3:利用第一行和第一列来存储每行和每列的0信息,但首先要判断第一行和第一列是不是存在0,只需要两个bool行变量。

class Solution {</span>
public:
    void setZeroes(vector<vector<int>>& matrix) {
        if(matrix.empty()) //空
        {
            return;
        }
        
        int rowSize = matrix.size(), colSize = matrix[0].size();
        bool firstRowZero = false, firstColZero = false;
        //记录第一行和第一列是否有0
        for(int row = 0; row < rowSize; ++row)//第一列是否存在0
        {
            if(matrix[row][0] == 0)
            {
                firstColZero = true;
                break;
            }
        }
        for(int col = 0; col < colSize; ++col)//第一行是否存在0
        {
            if(matrix[0][col] == 0)
            {
                firstRowZero = true;
                break;
            }
        }
        //将本行和本列的0信息存在第一行和第一列中,当一行(列)中有0时,该行(列)的第一个元素同样要清0
        for(int row = 1; row < rowSize; ++row)
        {
            for(int col = 1; col < colSize; ++col)
            {
                if(matrix[row][col] == 0) //该行和列存在0,在第一行和第一列做记录
                {
                    matrix[row][0] = 0;
                    matrix[0][col] = 0;
                }
            }
        }
        
        for(int col = 1; col < colSize; ++col)//清除存在0的列
        {
            if(matrix[0][col] == 0)//某列有0
            {
                for(int index = 1; index < rowSize; ++index) //清0此列
                {
                    matrix[index][col] = 0;
                }
            }
        }
        for(int row = 1; row < rowSize; ++row)//清除存在0的行
        {
            if(matrix[row][0] == 0)//某行有0
            {
                for(int index = 1; index < colSize; ++index)//清0次行
                {
                    matrix[row][index] = 0;
                }
            }
        }
        
        if(firstRowZero)//第一行有0
        {
            for(int col = 0; col < colSize; ++col)//第一行是否存在0
            {
                matrix[0][col] = 0;
            }
        }
        if(firstColZero)//第一列有0
        {
            for(int row = 0; row < rowSize; ++row)//第一列是否存在0
            {
                matrix[row][0] = 0;
            }
        }
        
        return;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值