题目描述
给定一个 m x n
的矩阵,如果一个元素为 0
,则将其所在行和列的所有元素都设为 0
。请使用 原地
算法。
示例1
示例2
提示:
m == matrix.length
n == matrix[0].length
1 <= m, n <= 200
-2^31 <= matrix[i][j] <= 2^31 - 1
方法一:使用标记数组
思路和算法
我们可以用两个标记数组分别记录每一行和每一列是否有零出现。
具体地,我们首先遍历该数组一次,如果某个元素为 0
,那么就将该元素所在的行和列所对应标记数组的位置置为 true
。最后我们再次遍历该数组,用标记数组更新原数组即可。
代码
void setZeroes(int** matrix, int matrixSize, int* matrixColSize) {// Get the number of rows and columns in the matrixint m = matrixSize;int n = matrixColSize[0];// Initialize arrays to keep track of rows and columns that need to be zeroedint row[m], col[n];memset(row, 0, sizeof(row)); // Initialize row array with zerosmemset(col, 0, sizeof(col)); // Initialize col array with zeros// Iterate through the matrix to find elements that are zerofor (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {if (!matrix[i][j]) { // If the element is zerorow[i] = col[j] = true; // Mark the corresponding row and column}}}// Iterate through the matrix to update elements based on row and column markersfor (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {if (row[i] || col[j]) { // If the row or column needs to be zeroedmatrix[i][j] = 0; // Set the element to zero}}}
}
复杂度分析
时间复杂度:O(mn)
,其中 m
是矩阵的行数,n
是矩阵的列数。我们至多只需要遍历该矩阵两次。
空间复杂度:O(m+n)
,其中 m
是矩阵的行数,n
是矩阵的列数。我们需要分别记录每一行或每一列是否有零出现。
方法二:使用两个标记变量
思路和算法
我们可以用矩阵的第一行和第一列代替方法一中的两个标记数组,以达到 O(1)
的额外空间。但这样会导致原数组的第一行和第一列被修改,无法记录它们是否原本包含 0
。因此我们需要额外使用两个标记变量分别记录第一行和第一列是否原本包含 0
。
在实际代码中,我们首先预处理出两个标记变量,接着使用其他行与列去处理第一行与第一列,然后反过来使用第一行与第一列去更新其他行与列,最后使用两个标记变量更新第一行与第一列即可。
代码
void setZeroes(int** matrix, int matrixSize, int* matrixColSize) {int m = matrixSize; // Number of rows in the matrixint n = matrixColSize[0]; // Number of columns in the matrix// Flags to track if the first column or row needs to be zeroedint flag_col0 = false, flag_row0 = false;// Check the first column for zerosfor (int i = 0; i < m; i++) {if (!matrix[i][0]) {flag_col0 = true;}}// Check the first row for zerosfor (int j = 0; j < n; j++) {if (!matrix[0][j]) {flag_row0 = true;}}// Mark rows and columns for zeroing based on zero elements in the matrixfor (int i = 1; i < m; i++) {for (int j = 1; j < n; j++) {if (!matrix[i][j]) {matrix[i][0] = matrix[0][j] = 0;}}}// Zero out elements based on marked rows and columnsfor (int i = 1; i < m; i++) {for (int j = 1; j < n; j++) {if (!matrix[i][0] || !matrix[0][j]) {matrix[i][j] = 0;}}}// Zero out the first column if flaggedif (flag_col0) {for (int i = 0; i < m; i++) {matrix[i][0] = 0;}}// Zero out the first row if flaggedif (flag_row0) {for (int j = 0; j < n; j++) {matrix[0][j] = 0;}}
}
复杂度分析
时间复杂度:O(mn)
,其中 m
是矩阵的行数,n
是矩阵的列数。我们至多只需要遍历该矩阵两次。
空间复杂度:O(1)
。我们只需要常数空间存储若干变量。
作者:力扣官方题解
链接:https://leetcode.cn/problems/set-matrix-zeroes/solutions/669901/ju-zhen-zhi-ling-by-leetcode-solution-9ll7/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。