首页 > 其他 > 详细

Leetcode: Set Matrix Zeroes

时间:2015-04-19 22:49:04      阅读:268      评论:0      收藏:0      [点我收藏+]

题目:
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;

            }
        }
    }
};

Leetcode: Set Matrix Zeroes

原文:http://blog.csdn.net/theonegis/article/details/45133581

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!