【Hot100】LeetCode—73. 矩阵置零

发布于:2024-08-17 ⋅ 阅读:(82) ⋅ 点赞:(0)


1- 思路

开辟额外两个一维数组

  • 1- 利用额外的两个一维数组 boolean 数组空间,遇到 0 则将当前位置的元素设置为 true
    • 一维 row 数组:记录某一行是否为 true
    • 一维 col 数组:记录某一列是否为 true
  • 2- 根据 rowcol 数组遍历

2- 实现

⭐53. 最大子数组和——题解思路

在这里插入图片描述

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;
                }
            }
        }

        // 2.重新遍历
        for(int i = 0 ; i < m;i++){
            for(int j = 0 ; j < n;j++){
                if(row[i] || col[j]){
                    matrix[i][j] = 0;
                }
            }
        }
    }
}

3- ACM 实现

public class setZeros {

    public static void setZeros(int[][] matrix){
        // 1. 数据结构
        int m = matrix.length;
        int n = matrix[0].length;
        boolean[] row = new boolean[m];
        boolean[] col = new boolean[n];

        // 2.遍历
        for(int i= 0; i < m;i++){
            for(int j = 0 ; j < n ;j++){
                if(matrix[i][j]==0){
                    row[i] = col[j] = true;
                }
            }
        }
        // 3.遍历
        for(int i = 0 ; i < m;i++){
            for(int j = 0 ; j < n ;j++){
                if(row[i]||col[j]){
                    matrix[i][j] = 0;
                }
            }
        }

    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("输入数组行数m");
        int m = sc.nextInt();
        System.out.println("输入数组列数n");
        int n = sc.nextInt();
        int[][] matrix = new int[m][n];

        for(int i = 0 ; i < m;i++ ){
            for(int j = 0; j < n;j++){
                matrix[i][j] = sc.nextInt();
            }
        }
        setZeros(matrix);
        for(int[] mt :matrix){
            for(int i: mt){
                System.out.print(i+" ");
            }
            System.out.println();
        }
    }
}