leetcode - 73.Set Matrix Zeroes

    xiaoxiao2021-03-25  58

    Set Matrix Zeroes

    Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

    Solution1:

    better

    public void setZeroes(int[][] matrix) { int col0 = 1; int rows = matrix.length; int cols = matrix[0].length; for (int i = 0; i < rows; i++) { if (matrix[i][0] == 0) col0 = 0; for (int j = 1; j < cols; j++) { if (matrix[i][j] == 0) { matrix[i][0] = 0; matrix[0][j] = 0; } } } for (int i = rows - 1; i >= 0; i--) { for (int j = cols - 1; j >= 1; j--) { if (matrix[i][0] == 0 || matrix[0][j] == 0) { matrix[i][j] = 0; } } if (col0 == 0) matrix[i][0] = 0; } }

    Solution2:

    public void setZeroes(int[][] matrix) { boolean fr = false; boolean fc = false; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { if (matrix[i][j] == 0) { if (i == 0) fr = true; if (j == 0) fc = true; matrix[0][j] = 0; matrix[i][0] = 0; } } } for (int i = 1; i < matrix.length; i++) { for (int j = 1; j < matrix[0].length; j++) { if (matrix[i][0] == 0 || matrix[0][j] == 0) { matrix[i][j] = 0; } } } if (fr) { for (int j = 0; j < matrix[0].length; j++) { matrix[0][j] = 0; } } if (fc) { for (int i = 0; i < matrix.length; i++) { matrix[i][0] = 0; } } }
    转载请注明原文地址: https://ju.6miu.com/read-40585.html

    最新回复(0)