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?
public class Solution {
public void setZeroes(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return;
int row = matrix.length, col = matrix[0].length, row0 = 1;
for (int i = 0; i < row; i++) {
if (matrix[i][0] == 0) row0 = 0;
for (int j = 1; j < col; j++) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for (int i = row-1; i >= 0; i--) {
for (int j = col-1; j >= 1; j--) {
if (matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0;
}
if (row0 == 0) matrix[i][0] = 0;
}
}
}
本文介绍了一种高效的算法,用于处理给定的矩阵:当矩阵中的某个元素为0时,将其所在的整行和整列设置为0。该算法采用原地修改的方式,并探讨了如何在不使用额外空间的情况下实现这一目标。
258

被折叠的 条评论
为什么被折叠?



