73. Set Matrix Zeroes

来源:互联网 发布:python时间戳 编辑:程序博客网 时间:2024/05/14 04:41

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?

最简单的思路:O(m+n),创建两个数组,记录数组元素为0对应的行和列,然后清零;

class Solution {public:    void setZeroes(vector<vector<int>>& matrix) {        int rows = matrix.size();        int cols = matrix[0].size();        vector<int> row(rows, -1);        vector<int> col(cols, -1);        for(int i = 0; i < rows; ++i){            for(int j = 0; j < cols; ++j){                if(matrix[i][j] == 0){                        col[j] = j;                        row[i] = i;                }             }        }        for(int i = 0; i < rows; ++i){            if(i == row[i]){                for(int n = 0; n < cols; ++n)                    matrix[i][n] = 0;            }        }        for(int j = 0; j < cols; ++j){            if(j == col[j]){                for(int m = 0; m < rows; ++m)                    matrix[m][j] = 0;            }        }    }};

O(1)思路:
http://www.cnblogs.com/grandyang/p/4341590.html
- 先扫描第一行第一列,如果有0,则将各自的flag设置为true
- 然后扫描除去第一行第一列的整个数组,如果有0,则将对应的第一行和第一列的数字赋0
- 再次遍历除去第一行第一列的整个数组,如果对应的第一行和第一列的数字有一个为0,则将当前值赋0
- 最后根据第一行第一列的flag来更新第一行第一列

class Solution {public:    void setZeroes(vector<vector<int>>& matrix) {        int rows = matrix.size();        int cols = matrix[0].size();        bool firstRows = false;        bool firstCols = false;        for(int i = 0; i < cols; ++i){            if(matrix[0][i] == 0){                firstRows = true;                break;            }        }        for(int j = 0; j < rows; ++j){            if(matrix[j][0] == 0){                firstCols = true;                break;            }        }        for(int i = 1; i < rows; ++i){            for(int j = 1; j < cols; ++j){                if(matrix[i][j] == 0){                    matrix[0][j] = 0;                    matrix[i][0] = 0;                }            }        }        for(int i = 1; i < cols; ++i){            if(matrix[0][i] == 0){                for(int m = 1; m < rows; ++m)                    matrix[m][i] = 0;            }        }        for(int j = 1; j < rows; ++j){            if(matrix[j][0] == 0){                for(int m = 1; m < cols; ++m)                    matrix[j][m] = 0;            }        }        if(firstRows){            for(int i = 0; i < cols; ++i)                   matrix[0][i] = 0;        }        if(firstCols){            for(int j = 0; j < rows; ++j)                matrix[j][0] = 0;        }    }};
0 0
原创粉丝点击