Description
Given an 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?
Examples
Example 1:
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
Example 2:
Input: matrix = [[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]]
解题思路
那他要in-place的修改,又要求尽量少的额外数据存储空间,(我能想到的)就是把“0”的行列号存下来,然后统一处理。
代码
可以优化的地方就是需要改成“0”的行列序号的存储
class Solution {
public void setZeroes(int[][] matrix) {
List<Integer> column = new ArrayList<>();
List<Integer> row = new ArrayList<>();
int i, j;
for(i = 0; i < matrix.length; i++)
for(j = 0; j < matrix[0].length; j++){
if(matrix[i][j] == 0){
column.add(j);
row.add(i);
}
}
for(Integer c: column){
for(i = 0; i < matrix.length; i++)
matrix[i][c] = 0;
}
for(Integer r: row){
for(j = 0; j < matrix[0].length; j++)
matrix[r][j] = 0;
}
}
}