73. Set Matrix Zeroes
Medium
993189FavoriteShare
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
Example 1:
Input:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
Output:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
Example 2:
Input:
[
[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]
]
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?
今天终于做到一道简单点的题。一次就过了。
解题思路是用两个数组cr和cc先记录下需要清零的行和列,然后按照数组中的记录清零,就这么简单。
我的答案就在下面。然后我想解读一下solution中的各种解法,下面是我简单翻译的各种解题思路:
Approach 1: Additional Memory Approach这个和我的方法差不多
Approach 2: Brute O(1) space.这个的解法是过滤第一遍时如果遇到x[i][j]==0,就把i行和j列中非0的数变为最小负数。为什么变成最小负数而不是0呢?原因是因为如果变成0,同一行都变成0了,那如果这行中后面的列原来是0,那就会漏掉这一列。
会出现下面的情况:
Input: [ [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] ]
实际的错误输出:
[
[0,0,0,0],
[0,4,5,2],
[0,3,1,5]
]
最后一列被漏掉了,因为在做[0][0]时把最后一列处理了。
历过一遍后,再历一遍,把最小负数的空改为0就行了。
Approach 3: O(1) Space, Efficient Solution这个方法同方法一,改进的地方是不使用额外的数组来记录需要清零的行和列,而是用首行和首列来记录。
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int rows=matrix.size();
if(rows==0)return;
int cols=matrix[0].size();
if(cols==0)return;
vector<int> cr;//需要清零的行
vector<int> cc;//需要清零的列
cr.clear();
cc.clear();
vector<int>::iterator itcr;
vector<int>::iterator itcc;
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
if(matrix[i][j]==0)
{
itcr=find(cr.begin(),cr.end(),i);
itcc=find(cc.begin(),cc.end(),j);
if(itcr==cr.end())cr.push_back(i);
if(itcc==cc.end())cc.push_back(j);
}
}
}
for(int i=0;i<cr.size();i++)
{
int p=0;
while(p<cols)
{
matrix[cr[i]][p]=0;
p++;
}
}
for(int i=0;i<cc.size();i++)
{
int p=0;
while(p<rows)
{
matrix[p][cc[i]]=0;
p++;
}
}
return;
}
};