LeetCode | 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。空间复杂度O(m+n)。由于题目中提到in place的要求,所以我们可以考虑利用第一行和第一列来存储行/列是否为0的信息。

代码:

class Solution {
public:
    void setZeroes(vector<vector<int> > &matrix) {
        if(matrix.size()==0)
        {
            return;
        }
        bool* row = new bool[matrix[0].size()];
        bool* line = new bool[matrix.size()];
        for(int i=0;i<matrix.size();i++)
        {
            line[i] = false;
        }
        for(int i=0;i<matrix[0].size();i++)
        {
            row[i] = false;
        }
        for(int i=0;i<matrix.size();i++)
        {
            for(int j=0;j<matrix[0].size();j++)
            {
                if(matrix[i][j]==0)
                {
                    line[i]=true;
                    row[j]=true;
                }
            }
        }
        
        for(int i=0;i<matrix.size();i++)
        {
            for(int j=0;j<matrix[0].size();j++)
            {
                if(line[i]||row[j])
                {
                    matrix[i][j]=0;
                }
            }
        }
    }
};

class Solution {
public:
    void setZeroes(vector<vector<int> > &matrix) {
        bool firstLine = false;
        bool firstRow = false;
        for(int i=0;i<matrix[0].size();i++)
        {
            if(matrix[0][i] == 0){
                firstLine = true;
                break;
            }
        }
        
        for(int i=0;i<matrix.size();i++)
        {
            if(matrix[i][0] == 0){
                firstRow = true;
                break;
            }
        }
        
        for(int i=1;i<matrix.size();i++)
        {
            for(int j=1;j<matrix[0].size();j++)
            {
                if(matrix[i][j] == 0)
                {
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }
        
        for(int i=1;i<matrix.size();i++)
        {
            for(int j=1;j<matrix[0].size();j++)
            {
                if(matrix[i][0] == 0 || matrix[0][j] == 0)
                {
                    matrix[i][j]=0;
                }
            }
        }
        
        if(firstLine){
            for(int i=0;i<matrix[0].size();i++)
            {
                matrix[0][i] = 0;
            }
        }
        
        if(firstRow){
            for(int i=0;i<matrix.size();i++)
            {
                matrix[i][0] = 0;
            }
        }
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/17327193
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞