题目链接:https://leetcode.cn/problems/set-matrix-zeroes/description/?envType=study-plan-v2&envId=top-100-liked
打标记
class Solution {
public void setZeroes(int[][] matrix) {
int n = matrix.length;
int m = matrix[0].length;
//打标记,如果是0就标记为1
int[][] cnt = new int[n][m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(matrix[i][j] == 0){
cnt[i][j] = 1;
}
}
}
//对打上标记的位置操作
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(cnt[i][j] == 1){
for(int k = 0; k < n; k++){
matrix[k][j] = 0;
}
for(int k = 0; k < m; k++){
matrix[i][k] = 0;
}
}
}
}
}
}
//优化
class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;
boolean[] row = new boolean[m];
boolean[] col = new boolean[n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0) {
row[i] = col[j] = true;
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (row[i] || col[j]) {
matrix[i][j] = 0;
}
}
}
}
}
还剩82题!