前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode: Set Matrix Zeroes

Leetcode: Set Matrix Zeroes

作者头像
卡尔曼和玻尔兹曼谁曼
发布2019-01-22 15:17:12
3810
发布2019-01-22 15:17:12
举报

题目: Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. 提示: 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?

思路分析: 用O(mn) 空间,只要再构造一个matrix即可。 用O(m + n)空间,只需创建两个向量,第一个向量记录哪些行为0,第二个向量记录哪些列为0即可。 使用固定空间的算法:利用矩阵的第一行和第一列记录哪些行和哪些列为0,但得先用两个变量记录矩阵的第一行和第一列是否为0。

C++参考代码:

代码语言:javascript
复制
class Solution
{
public:
    void setZeroes(vector<vector<int> > &matrix)
    {
        size_t rows = matrix.size();
        size_t columns = matrix[0].size();
        if (!rows) return;
        bool isRowZero = false;
        bool isColumnZero = false;
        //判断第一行是否有0
        for (size_t i = 0; i < columns; ++i)
        {
            if (!matrix[0][i])
            {
                isRowZero = true;
                break;
            }
        }
        //判断第一列是否有0
        for (size_t i = 0; i < rows; ++i)
        {
            if (!matrix[i][0])
            {
                isColumnZero = true;
                break;
            }
        }
        //将行中有0的写入第一行,列中有0的写入第一列
        for (size_t i = 1; i < rows; ++i)
        {
            for (size_t j = 1; j < columns; ++j)
            {
                if (!matrix[i][j])
                {
                    matrix[0][j] = 0;
                    matrix[i][0] = 0;
                }
            }
        }
        //根据第一行和第一列的数字填充矩阵
        for (size_t i = 1; i < rows; ++i)
        {
            for (size_t j = 1; j < columns; ++j)
            {
                if (!matrix[i][0] || !matrix[0][j]) matrix[i][j] = 0;
            }
        }
        //处理第一行的情况
        if (isRowZero)
        {
            for (size_t i = 0; i < columns; ++i)
            {
                matrix[0][i] =0;
            }
        }
        //处理第一列的情况
        if (isColumnZero)
        {
            for (size_t i = 0; i < rows; ++i)
            {
                matrix[i][0] = 0;

            }
        }
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年04月19日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档