C++ code, easy to understand


  • 0
    M
    class Solution {
    public:
        void setZeroes(vector<vector<int>>& matrix) {
            int m = matrix.size();
            int n = matrix[0].size();
            vector<bool>row(m,false);
            vector<bool>col(n,false);
            for(int i = 0; i<m; i++)
                for(int j = 0; j<n; j++)
                {
                    if(matrix[i][j] == 0)
                    {
                    row[i] = true;
                    col[j] = true;
                    }
                }
            for(int i = 0; i<m; i++)
            {
                if(row[i] == true)
                fill(&matrix[i][0], &matrix[i][0]+n, 0);
            }
            for(int j = 0; j<n; j++)
            {
                if(col[j] == true)
                    for(int i = 0; i<m; i++)
                        matrix[i][j] = 0;
            }
            
        }
    };

  • 0
    L

    The problem said:

    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?

    Your answer uses O(m + n) space.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.