LeetCode 第 73 题 (Set Matrix Zeroes)

LeetCode 第 73 题 (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?

既然不让占用额外的空间,那我们就做的极致一点,整个代码中只建立了六个局部变量。除此之外不再使用任何存储空间。
代码的思路很简单,找到矩阵的第一个零元素。那么这个零元素所在的行和列都是要被清零的。所以我们可以用这个 0 元素所在的行和列来存储其他的 0 元素的位置。记录完所有的零元素的位置后,就可以清零工作了。唯一需要注意的是这一特殊的行和列要最后处理,因为提早把它清零了我们就失去其他零元素的位置信息了。

下面是代码:

void getFirstZerosPos(const vector<vector<int>>& matrix, int &row_, int &col_)
{
    int rows = matrix.size();
    int cols = matrix[0].size();
    for( int row = 0; row < rows; row++ )
    {
        for(int col = 0; col < cols; col ++ )
        {
            if(matrix[row][col] == 0)
            {
                col_ = col;
                row_ = row;
                return;
            }
        }
    }
    col_ = -1;
    row_ = -1;
    return;
}

void setZeroes(vector<vector<int>>& matrix)
{
    int ROWS = matrix.size();
    if(ROWS == 0) return;
    int COLS = matrix[0].size();
    int col0, row0;
    getFirstZerosPos(matrix, row0, col0);
    if(row0 == -1) return;
    for( int row = row0; row < ROWS; row++ )
    {
        for(int col = 0; col < COLS; col ++ )
        {
            if(matrix[row][col] == 0)
            {
                matrix[row][col0] = 0;
                matrix[row0][col] = 0;
            }
        }
    }
    for(int col = 0; col < COLS; col ++ )
    {
        if(col == col0) continue;
        if(matrix[row0][col] == 0)
        {
            for(int row = 0; row < ROWS; row++)
            {
                matrix[row][col] = 0;
            }
        }
    }
    for(int row = 0; row < ROWS; row++) //遍历这一列的各行
    {
        if(row == row0) continue;
        if(matrix[row][col0] == 0) //如果这行对应的元素为 0
        {
            for(int col = 0; col < COLS; col ++ ) //就将这一行全写为 0
            {
                matrix[row][col] = 0;
            }
        }
    }
    for(int row = 0; row < ROWS; row++)
    {
        matrix[row][col0] = 0;
    }
    for(int col = 0; col < COLS; col++)
    {
        matrix[row0][col] = 0;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值