【Java】【LeetCode】73. Set Matrix Zeroes

it2022-05-05  168

题目:

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

Example 1:

Input: [   [1,1,1],   [1,0,1],   [1,1,1] ] Output: [   [1,0,1],   [0,0,0],   [1,0,1] ]

Example 2:

Input: [   [0,1,2,0],   [3,4,5,2],   [1,3,1,5] ] Output: [   [0,0,0,0],   [0,4,5,0],   [0,3,1,0] ]

Follow up:

A straight forward solution using O(mn) space is probably a bad idea.A simple improvement uses O(m + n) space, but still not the best solution.Could you devise a constant space solution?

题解:

我们借用原矩阵的首行和首列来存储这个信息。如果我们直接将0存入首行或首列来表示相应行和列要置0的话,我们很难判断首行或者首列自己是不是该置0。这里我们用两个boolean变量记录下首行和首列原本有没有0,然后在其他位置置完0后,再单独根据boolean变量来处理首行和首列,就避免了干扰的问题。

- 先扫描第一行第一列,如果有0,则将各自的flag设置为true - 然后扫描除去第一行第一列的整个数组,如果有0,则将对应的第一行和第一列的数字赋0 - 再次遍历除去第一行第一列的整个数组,如果对应的第一行和第一列的数字有一个为0,则将当前值赋0 - 最后根据第一行第一列的flag来更新第一行第一列

代码如下:

public class SetMatrixZeroes { public static void main(String[] args) { /** * Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place. */ /** * Follow up: * * A straight forward solution using O(mn) space is probably a bad idea. * A simple improvement uses O(m + n) space, but still not the best solution. * Could you devise a constant space solution? */ /** * Example 1: * Input: * [ * [1,1,1], * [1,0,1], * [1,1,1] * ] * Output: * [ * [1,0,1], * [0,0,0], * [1,0,1] * ] */ int[][] matrix1 = { { 1, 1, 1 }, { 1, 0, 1 }, { 1, 1, 1 } }; setZeroes(matrix1); LeetCodeUtil.printIntTwoDimensionalArray(matrix1); /** * Input: * [ * [0,1,2,0], * [3,4,5,2], * [1,3,1,5] * ] * Output: * [ * [0,0,0,0], * [0,4,5,0], * [0,3,1,0] * ] */ int[][] matrix2 = { { 0, 1, 2, 0 }, { 3, 4, 5, 2 }, { 1, 3, 1, 5 } }; setZeroes(matrix2); LeetCodeUtil.printIntTwoDimensionalArray(matrix2); } public static void setZeroes(int[][] matrix) { if (matrix == null) { return; } boolean firstColumnHaveZero = false, firstRowHaveZero = false; // Does first column have zero? for (int i = 0; i < matrix.length; i++) { if (matrix[i][0] == 0) { firstColumnHaveZero = true; break; } } // Does first row have zero? for (int j = 0; j < matrix[0].length; j++) { if (matrix[0][j] == 0) { firstRowHaveZero = true; break; } } // find zeroes and store the info in first row and column for (int i = 1; i < matrix.length; i++) { for (int j = 1; j < matrix[0].length; j++) { if (matrix[i][j] == 0) { matrix[0][j] = 0; matrix[i][0] = 0; } } } // set zeroes except the first row and column 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; } } } // set zeroes for first row and column if needed if (firstColumnHaveZero) { for (int i = 0; i < matrix.length; i++) { matrix[i][0] = 0; } } if (firstRowHaveZero) { for (int j = 0; j < matrix[0].length; j++) { matrix[0][j] = 0; } } } }

最新回复(0)