题目链接:https://leetcode.com/problems/set-matrix-zeroes/
题目:
m x n
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(1),时间复杂度为O(m*n)。
1、判断数组左上边界是否有零
2、扫描除边界外数组元素,若有零在边界处标记
3、根据标记按行列处理边界外元素为0
4、若边界有零,则边界归0
算法:
public void setZeroes(int[][] matrix) {
boolean left = false;
boolean up = false;
for (int i = 0; i < matrix.length; i++) { // 左边界是否有零
if (matrix[i][0] == 0) {
left = true;
}
}
for (int i = 0; i < matrix[0].length; i++) {// 上边界是否有零
if (matrix[0][i] == 0) {
up = true;
}
}
for (int i = 1; i < matrix.length; i++) {
for (int j = 1; j < matrix[0].length; j++) {
if (matrix[i][j] == 0) {// 在边界处标记
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for (int i = 1; i < matrix.length; i++) {// 根据左边界标记按行处理标记外数组
if (matrix[i][0] == 0) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = 0;
}
}
}
for (int i = 1; i < matrix[0].length; i++) {// 根据上边界标记按列处理标记外数组
if (matrix[0][i] == 0) {
for (int j = 0; j < matrix.length; j++) {
matrix[j][i] = 0;
}
}
}
if (left) {// 处理边界
for (int i = 0; i < matrix.length; i++) {
matrix[i][0] = 0;
}
}
if (up) {
for (int i = 0; i < matrix[0].length; i++) {
matrix[0][i] = 0;
}
}
}