A 88ms C++ Constant Space Solution


  • 0
    Y
    class Solution {
    public:
        void setZeroes(vector<vector<int>>& matrix) {
            int nRow = matrix.size();
            int nCol = matrix[0].size();
            int i, j;
            bool firstC = false, firstR = false;
            
            for(i = 0; i < nRow; i++) {
                for(j = 0; j < nCol; j++) {
                    if(matrix[i][j] == 0) {
                        if(i == 0) firstR = true;
                        if(j == 0) firstC = true;
                        else { 
                            matrix[0][j] = 0;
                            matrix[i][0] = 0;
                        }
                    }
                }
            }
            for(i = 1; i < nRow; i++) if(matrix[i][0] == 0) for(j = 1; j < nCol; j++) matrix[i][j] = 0;
            
            for(j = 1; j < nCol; j++) if(matrix[0][j] == 0) for(i = 1; i < nRow; i++) matrix[i][j] = 0;
            
            if(firstR) for(j = 0; j < nCol; j++) matrix[0][j] = 0;
            if(firstC) for(i = 0; i < nRow; i++) matrix[i][0] = 0;
        }
    };

Log in to reply
 

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