题目链接:leetcoede 73. 矩阵置零
Given an m x n integer matrix matrix, if an element is 0
, set its entire row and column to 0
’s.
You must do it in place.
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
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
- -231 <= matrix[i][j] <= 231 - 1
Follow up:
- A straightforward 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?
思路:
- 做法1.暴力 : 复制一个一摸一样的数组,在原数组里遇到0,就将新数组对应的行列都赋值为0,最后输出行数组就是答案。时间复杂度为O(n3),空间复杂度也很高,这不是一个好方法。
- 做法2. 开两个一维数组,用来存放每行和每列是否需要被设置为0,时间复杂度为O(n2)
- 做法3.,用第一行和第一列来代替做法2的额外数组,来存放对应行和列是否需要被赋值为0的信息,然后用两个变量来表示第一行和第一列本身是否需要被赋值为0。时间复杂度为O(n2),但空间复杂度只有O(1)
做法3代码实现:
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
// 特判,如果行列为空
if(matrix.empty() || matrix[0].empty()) return;
// n行数 m列数 r0第0行是否有0 c0类似
int n = matrix.size(), m = matrix[0].size();
int r0 = 1, c0 = 1;
// 判断第0行和第0列
for(int j = 0; j < m; j ++ ){
if(matrix[0][j] == 0) r0 = 0;
}
for(int i = 0; i < n; i ++ ){
if(matrix[i][0] == 0) c0 = 0;
}
// 判断中间
for(int i = 1; i < n; i ++ ){
for(int j = 1; j < m; j ++ ){
if(matrix[i][j] == 0){
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
// 给中间部分赋值
for(int i = 1; i < n; i ++ ){
if(matrix[i][0] == 0){
for(int j = 0; j < m; j ++ ){
matrix[i][j] = 0;
}
}
}
for(int j = 1; j < m; j ++ ){
if(matrix[0][j] == 0){
for(int i = 0; i < n; i ++ ){
matrix[i][j] = 0;
}
}
}
//给第一行和第一列赋值
if(!r0)
for(int j = 0; j < m; j ++)
matrix[0][j] = 0;
if(!c0)
for(int i = 0; i < n; i ++)
matrix[i][0] = 0;
}
};