題目
Given a mxn 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?
分析
空間復雜度為O(m*n)的方法很簡單,直接復制矩陣,然后在新的矩陣空間中進行操作即可。
空間復雜度為O(m+n)的方法,則通過兩個一維數組來分別記錄每一行是否需要變為0。
空間復雜度為O(1)的方法則使用矩陣的第一行和第一列來記錄,并使用兩個單獨的變量來記錄第一行和第一列是否需要歸零。在進行完矩陣其余部分的歸零操作后,再據此對第一行和第一列進行歸零操作。
實現
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int m=matrix.size(), n=matrix[0].size();
bool row0=false, col0=false;
for(int i=0; i<m; i++)
if(matrix[i][0]==0) col0=true;
for(int j=0; j<n; j++)
if(matrix[0][j]==0) row0=true;
for(int i=1; i<m; i++){
for(int j=1; j<n; j++){
if(matrix[i][j]==0){
matrix[i][0]=0;
matrix[0][j]=0;
}
}
}
for(int i=1; i<m; i++)
if(matrix[i][0]==0)
for(int j=1; j<n; j++)
matrix[i][j]=0;
for(int j=1; j<n; j++)
if(matrix[0][j]==0)
for(int i=1; i<m; i++)
matrix[i][j]=0;
if(col0)
for(int i=0; i<m; i++)
matrix[i][0]=0;
if(row0)
for(int j=0; j<n; j++)
matrix[0][j]=0;
}
};
思考
無=_=