Straightforward Solution using c++


  • 0
    W

    A straightforward solution using C++, using O(m+n) space.
    The basic idea is record which row and column needs to be set zero then change the numbers one by one.
    The time complexity is O(m*n)

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

Log in to reply
 

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