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:
Did you use extra space?
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?
这道题目虽然是中等难度,但是其实并不难,就是col和row很烦一定要搞清楚了,最好找个纸写下来
思路,主要针对O(1) Space:
- 检查0行0列是否有0
- 检查所有行和列,如果有0,设置第1行/第1列为0
- 分别检查第0行和第0列,如果有0,设置第1排/第1列开始为0
- 使用之前检查的0行0列,如果有0,设置行/列为0
public class Solution { public void setZeroes(int[][] matrix) { int row = matrix.length; int col = matrix[0].length; boolean brow = false; boolean bcol = false; //check if frist row for(int i=0;i<row;i++){ if(matrix[i][0] == 0){ bcol = true; } } for(int i=0;i<col;i++){ if(matrix[0][i] == 0 ){ brow = true; } } //if has 0 set first item to 0 for(int i=0;i<row;i++){ for(int j=0;j<col;j++){ if(matrix[i][j] == 0){ matrix[i][0] = 0; matrix[0][j] = 0; } } } //for testing, printout matrix // for (int i = 0; i < matrix.length; i++) { // for (int j = 0; j < matrix[i].length; j++) { // System.out.print(matrix[i][j] + " "); // } // System.out.println(); // } //change to 0 from row and col 1 for(int i=1;i<col;i++){ if(matrix[0][i] == 0){ for(int j=1;j<row;j++){ matrix[j][i] =0; } } } for(int i=1;i<row;i++){ if(matrix[i][0] == 0){ for(int j=1;j<col;j++){ matrix[i][j] =0; } } } //change row 0 and col 0 System.out.println(col); if(bcol){ for(int j=0;j<row;j++){ matrix[j][0] =0; } } if(brow){ for(int i=0;i<col;i++){ matrix[0][i] = 0; } } } }