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.
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?
---
T: O(m^n)
S: O(m+n)
public class Solution { public void setZeroes(int[][] matrix) { int m = matrix.length; int n = matrix[0].length; int[] col = new int[m]; int[] row = new int[n]; for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(matrix[i][j] == 0){ col[i] = 1; row[j] = 1; } } } for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(col[i] == 1 || row[j] == 1) matrix[i][j] = 0; } } } }
constant space solution
浙公网安备 33010602011771号