Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Have you met this question in a real interview?Given a matrix
[
[1,2],
[0,3]
],
return [ [0,2], [0,0] ]
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)的空間複雜度的實現,這就不多說了;這裏主要講下如何做到常數空間,採用的方法是位圖,用vector<unsigned> row, col中的每個數的每一位對應相應的行,所以空間複雜度爲O(n/32 + m/32),這樣1000 * 1000的矩陣的空間也才60多個整數空間,代碼如下:
class Solution {
public:
/**
* @param matrix: A list of lists of integers
* @return: Void
*/
//位向量,定義兩個位向量
void setZeroes(vector<vector<int> > &matrix) {
// write your code here
int n = matrix.size();
if(n < 1)
return;
int m = matrix[0].size();
int Max = max(m / 32, n / 32) + 1;
vector<unsigned> row(Max, ~0), col(Max, ~0);
for(int i = 0; i < n; ++i){
for(int j = 0; j < m; ++j){
if(matrix[i][j] == 0){
row[i >> 5] = row[i >> 5] & ~(1 << (i % 32));
col[j >> 5] = col[j >> 5] & ~(1 << (j % 32));
}
}
}
for(int i = 0; i < n; ++i){
for(int j = 0; j < m; ++j)
if(!((row[i >> 5] & (1 << (i % 32))) && (col[j >> 5] & (1 << (j % 32)))))
matrix[i][j] = 0;
}
}
};