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.

click to show follow up.

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.如果每遇到0就把它的行和列全部置为0,这就不对了,因为这样会带入新的0到矩阵中。借助空间复杂度为O(m+n),遍历矩阵,将遇到的每一个0元素所在的行和列标记起来,最后在遍历矩阵,若某元素的所在行或列被标记,则就被置为0.

class Solution {
public:
    void setZeroes(vector<vector<int> > &matrix) {
        int m=matrix.size();
        int n=matrix[0].size();
        if(m==0||n==0)
            return;
        int *mFlag=new int[m]();
        int *nFlag=new int[n]();
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(matrix[i][j]==0)
                {
                    mFlag[i]=1;
                    nFlag[j]=1;
                }
            }
        }
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(mFlag[i]||nFlag[j])
                {
                    matrix[i][j]=0;
                }
            }
        }
        delete[] mFlag;
        delete[] nFlag;
    }
};

这道题说O(m+n)空间复杂度不是最好的答案,意味着还有更优化的空间复杂度,那只有O(1)的空间复杂度。这样就会带来时间复杂度的增加。如此这样做,我还没有想好如何破.

原文地址:https://www.cnblogs.com/awy-blog/p/3625650.html