思路
首先遍历数组,将出现零的行和列标记出来
解题过程
再次遍历数组,如果某元素的同行或同列已经被标记了(即有零元素),那么将该元素置零
Code
class Solution {public void setZeroes(int[][] matrix) {int m = matrix.length;int 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;}}}}
}作者:菜卷
链接:https://leetcode.cn/problems/set-matrix-zeroes/solutions/2962388/ju-zhen-zhi-ling-by-ashi-jian-chong-dan-2rado/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。