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?
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]]
Constraints:
m == matrix.length
n == matrix[0].length
1 <= m, n <= 200
-10^9 <= matrix[i][j] <= 10^9
C++
- O ( M N ) O(MN) O(MN) 时间复杂度, O ( 1 ) O(1) O(1) 空间复杂度
- 思路是将第一行和第一列作为标志
- 打完标记后再逆着根据标记置零
- 细节还是有的,比如要选择把第一行或者第一列空出来,然后选择对应的第一列的标记或者第一行的标记
- 代码中的写法是空出了第一列,然后用一个额外变量来记录第一列是否置零
class Solution {
public:
void setZeroes(vector<vector<int>>& a) {
int n=a.size(),m=a[0].size();
bool col=false;
for(int i=0;i<n;i++){
if(!a[i][0])col=true;
for(int j=1;j<m;j++)
if(!a[i][j])
a[i][0]=a[0][j]=0;
}
for(int i=n-1;i>=0;i--){
for(int j=m-1;j>=1;j--)
if(!a[i][0]||!a[0][j])
a[i][j]=0;
if(col)a[i][0]=0;
}
}
};
Java
class Solution {
public void setZeroes(int[][] a) {
int n=a.length,m=a[0].length;
boolean col=false;
for(int i=0;i<n;i++){
if(a[i][0]==0)col=true;
for(int j=1;j<m;j++)
if(a[i][j]==0)
a[i][0]=a[0][j]=0;
}
for(int i=n-1;i>=0;i--){
for(int j=m-1;j>=1;j--)
if(a[i][0]==0||a[0][j]==0)
a[i][j]=0;
if(col)a[i][0]=0;
}
}
}
Python
class Solution:
def setZeroes(self, a: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n,m,col=len(a),len(a[0]),False
for i in range(n):
if a[i][0]==0:
col=True
for j in range(1,m):
if a[i][j]==0:
a[i][0]=a[0][j]=0
for i in range(n-1,-1,-1):
for j in range(m-1,0,-1):
if a[i][0]==0 or a[0][j]==0:
a[i][j]=0
if col:
a[i][0]=0
Go
func setZeroes(a [][]int) {
n,m,col:=len(a),len(a[0]),false
for i:=0;i<n;i++ {
if a[i][0]==0 {
col=true
}
for j:=1;j<m;j++ {
if a[i][j]==0 {
a[i][0],a[0][j]=0,0
}
}
}
for i:=n-1;i>=0;i-- {
for j:=m-1;j>=1;j-- {
if a[i][0]==0 || a[0][j]==0 {
a[i][j]=0
}
}
if col {
a[i][0]=0
}
}
}