版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/toward_south/article/details/89682852
题目:
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Follow up:
Did you use extra space?
A straight forward solution using O(m n) 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?
题意:
给定一个mxn矩阵,如果一个元素是0,把它的行和列都设为0,但是这里有个要求,就是希望我们能用O(1)的空间来解决问题
解题思路:
由于题目要求空间使用复杂度为O(1),所以我们可以使用row(第一行),col(第一列) 两个boolean变量来标记每一行或每一列是否为0
通过遍历第一行第一列是否有0,有的话就让各自的 行标记、列标记为true,跳出循环(因为只要有一个为0,那么该行或列就已经可以当做为0了,没必要再往下遍历)
再遍历除第一行和第一列的数组,判断某个数值是否为0,如果是的话,就标记那个数值的行和列为0
再次遍历除第一行和第一列的数组,判断第一行或第一列是否存在有0的数值,有的话就标记当前数值为0
最后分别判断行列标识,分别将为0的行或列置为0就行
Java实现:
public void setZeroes(int[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return;
}
boolean row = false;
boolean col = false;
for(int i = 0;i < matrix[0].length;i++) {
if(matrix[0][i] == 0) {
row = true;
break;
}
}
for(int i = 0;i < matrix.length;i++) {
if(matrix[i][0] == 0) {
col = true;
break;
}
}
for(int i = 1;i < matrix.length;i++) {
for(int j = 1;j < matrix[0].length;j++) {
if(matrix[i][j] == 0) {
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
for(int i = 1;i < matrix.length;i++) {
for(int j = 1;j < matrix[0].length;j++) {
if(matrix[0][j] == 0 || matrix[i][0] == 0) {
matrix[i][j] = 0;
}
}
}
if(row) {
for(int i = 0;i < matrix[0].length;i++) {
matrix[0][i] = 0;
}
}
if(col) {
for(int i = 0;i < matrix.length;i++) {
matrix[i][0] = 0;
}
}
}