73. 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.
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
这是什么沙雕题目??我也够沙雕的,题没读完就开始码,看清楚要的是空间复杂度O(m+n)
那么哪来的m哪来的n呢?
发现一行有m个元素,一列有n个元素,所以分别给行和列设置boolean数组。然后对每个元素扫描,扫描 ij 是0,那就给两个数组赋true。
最后回来set 0,那就是扫描行boolean数组,用Arrays.fill(数组名,fill的值)进行fill。然后扫描列boolean数组,老老实实补0就完事了。
法克
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]=true; col[j]=true; } } } for(int i = 0; i < m; i++){ if(row[i]){ Arrays.fill(matrix[i],0); } } for(int j = 0; j < n; j++){ if(col[j]){ for(int i = 0; i < m; i++){ matrix[i][j]=0; } } } } }