Leetcode: Set Matrix Zeroes

来源:互联网 发布:淘宝类目怎么编辑分类 编辑:程序博客网 时间:2024/06/03 14:33

题目:
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++参考代码:

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;            }        }    }};
0 0