Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
解题思路:
用两个boolean数组row col表示行列是否有零即可,JAVA实现如下:
public void setZeroes(int[][] matrix) { if (matrix.length == 0 || matrix[0].length == 0) return; boolean[] row = new boolean[matrix.length], col = new boolean[matrix[0].length]; for (int i = 0; i < matrix.length; i++) for (int j = 0; j < matrix[0].length; j++) if (matrix[i][j] == 0) { row[i] = true; col[j] = true; } for (int i = 0; i < matrix.length; i++) for (int j = 0; j < matrix[i].length; j++) if (row[i] || col[j]) matrix[i][j] = 0; }
时间: 2024-10-20 02:51:56