【LeetCode】73. Set Matrix Zeroes (2 solutions)
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?
解法一:
使用数组分别记录需要置零的行列。然后根据数组信息对相应行列置零。
空间复杂度O(m+n)
class Solution { public: void setZeroes(vector<vector<int> > &matrix) { if(matrix.empty() || matrix[0].empty()) return; 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 ++) { for(int j = 0; j < n; j ++) { if(row[i] == true) matrix[i][j] = 0; if(col[j] == true) matrix[i][j] = 0; } } } };
解法二:
使用第一行和第一列记录该行和该列是否应该置零。
对于由此覆盖掉的原本信息,只要单独遍历第一行第一列判断是否需要置零即可。
空间复杂度O(1)
class Solution { public: void setZeroes(vector<vector<int> > &matrix) { if(matrix.empty() || matrix[0].empty()) return; int m = matrix.size(); int n = matrix[0].size(); bool col0 = false; bool row0 = false; for(int i = 0; i < m; i ++) { if(matrix[i][0] == 0) { col0 = true; break; } } for(int j = 0; j < n; j ++) { if(matrix[0][j] == 0) { row0 = true; break; } } for(int i = 1; i < m; i ++) { for(int j = 1; j < n; j ++) { if(matrix[i][j] == 0) { matrix[0][j] = 0; matrix[i][0] = 0; } } } for(int i = 1; i < m; i ++) { if(matrix[i][0] == 0) { for(int j = 1; j < n; j ++) { matrix[i][j] = 0; } } } for(int j = 1; j < n; j ++) { if(matrix[0][j] == 0) { for(int i = 1; i < m; i ++) { matrix[i][j] = 0; } } } if(col0 == true) { for(int i = 0; i < m; i ++) { matrix[i][0] = 0; } } if(row0 == true) { for(int j = 0; j < n; j ++) { matrix[0][j] = 0; } } } };