【矩阵】73. 矩阵置零

题目

法1:自己想的笨蛋方法

class Solution {
   
    public void setZeroes(int[][] matrix) {
   
        Set<Integer> rowSet = new HashSet<>();
        Set<Integer> columnSet = new HashSet<>();
        for (int i = 0; i < matrix.length; ++i) {
   
            for (int j = 0; j < matrix[0].length; ++j) {
   
                if (matrix[i][j] == 0) {
   
                    rowSet.add(i);
                    columnSet.add(j);
                }
            }
        }
        for (int i = 0; i < matrix.length; ++i) {
   
            if (rowSet.contains(i)) {
   
                Arrays.fill(matrix[i], 0);
            }
        }
        for (int j = 0; j < matrix[0].length; ++j) {
   
            if (columnSet.contains(j)) {
   
                for (int i = 0; i < matrix.length; ++i) {
   
                    matrix[i][j] = 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;
                }
            }
        }
    }
}

作者:力扣官方题解
链接:https://leetcode.cn/problems/set-matrix-zeroes/solutions/669901/ju-zhen-zhi-ling-by-leetcode-solution-9ll7/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

法2:

放个链接,估计真遇到了也写不出来。。。
https://leetcode.cn/problems/set-matrix-zeroes/solutions/670278/xiang-jie-fen-san-bu-de-o1-kong-jian-jie-dbxd/?envType=study-plan-v2&envId=top-100-liked

相关推荐

  1. 矩阵73. 矩阵

    2023-12-06 19:12:01       40 阅读
  2. 73. 矩阵

    2023-12-06 19:12:01       34 阅读
  3. 73. 矩阵

    2023-12-06 19:12:01       33 阅读
  4. 73.矩阵

    2023-12-06 19:12:01       12 阅读
  5. 【中等】73. 矩阵

    2023-12-06 19:12:01       44 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-06 19:12:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-06 19:12:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-06 19:12:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-06 19:12:01       18 阅读

热门阅读

  1. API开发工具的特点与应用场景

    2023-12-06 19:12:01       35 阅读
  2. tomcat核心组件及LVS组成作用

    2023-12-06 19:12:01       31 阅读
  3. C# 文件/文件夹处理常用类 File,Directory,Path

    2023-12-06 19:12:01       37 阅读
  4. tensor.topk 以及tensor.argmax

    2023-12-06 19:12:01       36 阅读