`

LeetCode 73 - 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?

void setZeroes(vector<vector<int>>& matrix) {
    int m = matrix.size(), n = matrix[0].size();
    vector<bool> clearRow(m), clearCol(n);
    for(int i=0; i<m; i++) {
        for(int j=0; j<n; j++){
            if(!matrix[i][j]) {
                clearRow[i] = true;
                clearCol[j] = true;
            }
        }
    }
    for(int i=0; i<m; i++) {
        for(int j=0; j<n; j++) {
            if(clearRow[i] || clearCol[j]) {
                matrix[i][j] = 0;;
            }
        }
    }
}

Space Complexity: O(M+N).  

 

void setZeroes(vector<vector<int>>& matrix) {
    int m = matrix.size(), n = matrix[0].size();
    bool clear1stRow = false, clear1stCol = false;
    for(int i=0; i<m; i++) {
        if(!matrix[i][0]) {
            clear1stCol = true; break;
        }
    }
    for(int j=0; j<n; j++){
        if(!matrix[0][j]) {
            clear1stRow = true; break;
        }
    }
    for(int i=1; i<m; i++) {
        for(int j=1; j<n; j++) {
            if(!matrix[i][j]) {
                matrix[0][j] = 0;
                matrix[i][0] = 0;
            }
        }
    }
    for(int i=1; i<m; i++) {
        for(int j=1; j<n; j++) {
            if(!matrix[i][0] || !matrix[0][j]) {
                matrix[i][j] = 0;
            }
        }
    }
    if(clear1stRow) {
        matrix[0].assign(n,0);
    }
    if(clear1stCol) {
        for(int i=0; i<m; i++) {
            matrix[i][0] = 0;
        }
    }
}

Space Complexity: O(1)

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics