题目描述:
给定一个 m x n 的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0。请使用原地算法。
示例 1:
输入:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
输出:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
示例 2:
输入:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
输出:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
进阶:
一个直接的解决方案是使用 O(mn) 的额外空间,但这并不是一个好的解决方案。
一个简单的改进方案是使用 O(m + n) 的额外空间,但这仍然不是最好的解决方案。
你能想出一个常数空间的解决方案吗?
在真实的面试中遇到过这道题?
首先我想到的就是不使用额外的空间,但是时间复杂度可能会很高,每次遇到零,就将该行和该列的数字列为一个不会用到的数字,这里我躲避了所有的测试用例中出现的数字,然后对行和列都进行遍历,复杂度很高,代码
class Solution {
public void setZeroes(int[][] matrix) {
// 使用原地算法,首先碰到了0那么进行操作
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if(matrix[i][j] == 0){
change(i, j,matrix);
}
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if(matrix[i][j] == Integer.MAX_VALUE - 5){
matrix[i][j] = 0;
}
}
}
}
//将坐标为x,y的点行列设置为2,如果是0不变,用以区分是后来改变的还是一开始就是零
public void change(int x,int y,int [][] matrix){
// 改变行
for (int i = 0; i < matrix.length; i++) {
if(matrix[i][y] != 0){
matrix[i][y] = Integer.MAX_VALUE - 5;
}
}
// 改变列
for (int i = 0; i < matrix[0].length; i++) {
if(matrix[x][i] != 0){
matrix[x][i] = Integer.MAX_VALUE - 5;
}
}
}
}
看一下官方的解答:
矩阵置零
class Solution {
public void setZeroes(int[][] matrix) {
Boolean isCol = false;
int R = matrix.length;
int C = matrix[0].length;
for (int i = 0; i < R; i++) {
// Since first cell for both first row and first column is the same i.e. matrix[0][0]
// We can use an additional variable for either the first row/column.
// For this solution we are using an additional variable for the first column
// and using matrix[0][0] for the first row.
if (matrix[i][0] == 0) {
isCol = true;
}
for (int j = 1; j < C; j++) {
// If an element is zero, we set the first element of the corresponding row and column to 0
if (matrix[i][j] == 0) {
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
// Iterate over the array once again and using the first row and first column, update the elements.
for (int i = 1; i < R; i++) {
for (int j = 1; j < C; j++) {
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
matrix[i][j] = 0;
}
}
}
// See if the first row needs to be set to zero as well
if (matrix[0][0] == 0) {
for (int j = 0; j < C; j++) {
matrix[0][j] = 0;
}
}
// See if the first column needs to be set to zero as well
if (isCol) {
for (int i = 0; i < R; i++) {
matrix[i][0] = 0;
}
}
}
}