https://leetcode.cn/problems/zero-matrix-lcci/

标记数组

新建布尔数组标记下零元素的位置。

  1. public static void setZeroes(int[][] matrix) {
  2. boolean[] col = new boolean[matrix.length]; //行
  3. boolean[] row = new boolean[matrix[0].length]; //列
  4. for (int i = 0; i < matrix.length; i++) {
  5. for (int j = 0; j < matrix[0].length; j++) {
  6. if (matrix[i][j] == 0) {
  7. col[i] = true;
  8. row[j] = true;
  9. }
  10. }
  11. }
  12. for (int i = 0; i < matrix.length; i++) {
  13. for (int j = 0; j < matrix[0].length; j++) {
  14. if (col[i] || row[j]) {
  15. matrix[i][j] = 0;
  16. }
  17. }
  18. }
  19. }