Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. Could you devise a constant space solution?
思路:因为需要遍历整个矩阵,时间复杂度肯定需要O(m * n),对于空间复杂度而言,第一种是可以使用O(m * n),对每个位置的0的情况进行记录,第二种是使用O(m + n),对每行每列是否存在0进行记录,第三种是O(1),即利用矩阵本身进行存储,借用矩阵第一行与第一列进行记录。
代码一:空间复杂度O(m + n)
class Solution { public: void setZeroes(vector<vector<int> > &matrix) { int m = matrix.size(); if(m == 0) return; int n = matrix[0].size(); if(n == 0) return; int row[m]; int column[n]; fill_n(row, m, 1); fill_n(column, n, 1); for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) if(matrix[i][j] == 0) { row[i] = 0; column[j] = 0; } for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) matrix[i][j] = (row[i] == 0 || column[j] == 0) ? 0 : matrix[i][j]; return; } };
代码二:空间复杂度O(1)
class Solution { public: void setZeroes(vector<vector<int> > &matrix) { int m = matrix.size(); if(m == 0) return; int n = matrix[0].size(); if(n == 0) return; // 判断第一行与第一列是否存在0 bool rowZero = false; bool columnZero = false; for(int i = 0; i < m; i++) if(matrix[i][0] == 0) { columnZero = true; break; } for(int i = 0; i < n; i++) if(matrix[0][i] == 0) { rowZero = true; break; } for(int i = 1; i < m; i++) for(int j = 1; j < n; j++) if(matrix[i][j] == 0) { matrix[i][0] = 0; matrix[0][j] = 0; } for(int i = 1; i < m; i++) for(int j = 1; j < n; j++) matrix[i][j] = (matrix[i][0] == 0 || matrix[0][j] == 0) ? 0 : matrix[i][j]; if(rowZero == true) for(int i = 0; i < n; i++) matrix[0][i] = 0; if(columnZero == true) for(int i = 0; i < m; i++) matrix[i][0] = 0; return; } };
【Leetcode】Set Matrix Zeroes
时间: 2024-10-03 13:40:11