LeetCode热题100--73.矩阵置零--中等

发布于:2025-05-09 ⋅ 阅读:(19) ⋅ 点赞:(0)

1. 题目

给定一个 m x n 的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。

示例 1:
请添加图片描述
输入:matrix = [[1,1,1],[1,0,1],[1,1,1]]
输出:[[1,0,1],[0,0,0],[1,0,1]]

示例 2:
请添加图片描述
输入:matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
输出:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]

2. 题解

class Solution {
    public void setZeroes(int[][] matrix) {
        int n = matrix.length;
        int m = matrix[0].length;
        boolean[] zeroInRow = new boolean[n];
        boolean[] zeroInLine = new boolean[m];
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++)
                if(matrix[i][j] == 0){
                    zeroInRow[i] = true;
                    zeroInLine[j] = true;
                }
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++)
                if(zeroInRow[i] || zeroInLine[j]){
                    matrix[i][j] = 0;
                }
    }
}

3. 解析

官方题解:矩阵置零

  1. class Solution {public void setZeroes(int[][] matrix)
    这定义了一个名为"Solution"的新类,并声明了setZeroes()方法来处理这个任务。
  2. int n = matrix.length;
    int m = matrix[0].length;
    boolean[] zeroInRow = new boolean[n];
    boolean[] zeroInLine = new boolean[m];
    这初始化了一些变量,用于存储行和列的信息。zeroInRow是一个布尔数组,如果对应行的元素为零,则它在该索引位置上将被设置为true。同样地,zeroInLine是一个布尔数组,表示相应列是否包含零。
  3. for(int i = 0; i < n; i++)
    for(int j = 0; j < m; j++)
    if(matrix[i][j] == 0){
    zeroInRow[i] = true;
    zeroInLine[j] = true;
    }
    这两个嵌套循环遍历整个矩阵。如果找到一个零元素,则将相应的zeroInRow[i]和zeroInLine[j]设置为true。
  4. for(int i = 0; i < n; i++)
    for(int j = 0; j < m; j++)
    if(zeroInRow[i] || zeroInLine[j]){
    matrix[i][j] = 0;
    }
    这两个嵌套循环遍历整个矩阵。如果对应的zeroInRow[i]或zeroInLine[j]为true,则将该位置上的元素设置为零。

网站公告

今日签到

点亮在社区的每一天
去签到