- 题目:输入一个二维数组matrix,如果matrix[i][j]为0,则将第i行和第j列的元素都设置为0
- 难度:Medium
- 思路:利用两个变量判断第0行和第0列本身是否需要设置为0,然后用数组中的第0行和第0列来存储第i行或者第j列需要设置为0
代码:
来自Discuss里的思路// Use first row and first column as markers. // if matrix[i][j] = 0, mark respected row and col marker = 0; indicating that later this respective row and col must be marked 0; // And because you are altering first row and collumn, you need to have two variables to track their own status. // So, for ex, if any one of the first row is 0, fr = 0, and at the end set all first row to 0;
public class Solution {
public void setZeroes(int[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return;
}
int rows = matrix.length;
int cols = matrix[0].length;
//因为将第i行或者第i列是否为需要设置0的标志用第0行或者第0列中的元素来标志,
//所以需要额外判断第0行或者第0列是否需要设置为0
boolean rf = false;//标志第0行是否全为0
boolean cf = false;//标志第0列是否全为0
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
if(matrix[i][j] == 0){
if(i == 0){
rf = true;
}
if(j == 0){
cf = true;
}
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
for(int i = 1; i < rows; i++){
for(int j = 1; j < cols; j++){
if(matrix[i][0] == 0 || matrix[0][j] == 0){
matrix[i][j] = 0;
}
}
}
if(rf){
for(int i = 0; i < cols; i++){
matrix[0][i] = 0;
}
}
if(cf){
for(int i = 0; i < rows; i++){
matrix[i][0] = 0;
}
}
}
}