Leetcode 73. Set Matrix Zeroes
Given an m x n
integer matrix matrix
, if an element is 0
, set its entire row and column to 0
. You must do it in place.
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
m == matrix.length
n == matrix[0].length
1 <= m, n <= 200
-2^31 <= matrix[i][j] <= 2^31 - 1
O(mn)
space is probably a bad idea.O(1)
space solution?public class Solution {
public void setZeroes(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
boolean firstRowHasZero = false;
boolean firstColHasZero = false;
// Determine if the first row or first column have any zeroes
for (int r = 0; r < rows; r++) {
if (matrix[r][0] == 0) {
firstColHasZero = true;
break;
}
}
for (int c = 0; c < cols; c++) {
if (matrix[0][c] == 0) {
firstRowHasZero = true;
break;
}
}
// Use first row and column to mark zero rows and cols
for (int r = 1; r < rows; r++) {
for (int c = 1; c < cols; c++) {
if (matrix[r][c] == 0) {
matrix[r][0] = 0;
matrix[0][c] = 0;
}
}
}
// Zero out cells based on the markers
for (int r = 1; r < rows; r++) {
for (int c = 1; c < cols; c++) {
if (matrix[r][0] == 0 || matrix[0][c] == 0) {
matrix[r][c] = 0;
}
}
}
// Zero out first row if needed
if (firstRowHasZero) {
for (int c = 0; c < cols; c++) {
matrix[0][c] = 0;
}
}
// Zero out first column if needed
if (firstColHasZero) {
for (int r = 0; r < rows; r++) {
matrix[r][0] = 0;
}
}
}
}
The time complexity of this solution is O(m * n)
because we essentially pass through the matrix a constant number of times:
The space complexity is O(1)
(constant space) aside from storing the input matrix, since we’re only using a few additional boolean variables.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?