我的思路是 ,用一个hash set存 每个为0点的坐标,然后取出来后迭代置0; 这样做的话也有毛病:处有重复置0的情况
struct VectorHash{
size_t operator() (const vector<int>& v) const{
hash<int> hasher;
size_t seed = 0;
for(int i: v){
seed ^= hasher(i) + 0x9e3779b9 + (seed << 6) + (seed >>2);
}
return seed;
}
};
struct Equal_Vector{
bool operator()(const vector<int>& v1, const vector<int>& v2 ) const{
return v1[0] == v2[0] && v1[1] == v2[1];
}
};
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 ;
}
// cout << " * "<< endl;
unordered_set<vector<int>, VectorHash, Equal_Vector> zero_pos;
for(int i=0; i<rows; ++i){
for(int j=0; j<cols; ++j){
if(matrix[i][j] == 0){
vector<int> temp;
temp.push_back(i);
temp.push_back(j);
zero_pos.insert(temp);
}
}
}
for(unordered_set<vector<int>,VectorHash, Equal_Vector >::iterator ite = zero_pos.begin(); ite != zero_pos.end(); ++ite){
int r = (*ite)[0];
int l = (*ite)[1];
// r -> 0
for(int i=0; i<cols ;++i){
matrix[r][i] = 0;
}
// l -> 0
for(int i=0; i<rows; ++i){
matrix[i][l] = 0;
}
}
}
};
其他解法:
先找行首列首是否有0, 用两个变量记录一下:是否要把行首、列首置零;
然后利用行首和列首 存当前矩阵 (该列。改行)是否置零的信息;
class Solution {
public void setZeroes(int[][] matrix) {
boolean rowFlag = false;
//判断首行
for (int i = 0; i < matrix[0].length; i++) {
if (matrix[0][i] == 0) {
rowFlag = true;
break;
}
}
boolean colFlag = false;
for (int i = 0; i < matrix.length; i++) {
if (matrix[i][0] == 0) {
colFlag = true;
break;
}
}
for (int i = 1; i < matrix.length; i++) {
for (int j = 1; j < matrix[0].length; j++) {
if (matrix[i][j] == 0){
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for (int i = 1; i < matrix[0].length; i++) {
if (matrix[0][i] == 0) {
for (int j = 0; j < matrix.length; j++) {
matrix[j][i] = 0;
}
}
}
for (int i = 1; i < matrix.length; i++) {
if (matrix[i][0] == 0) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = 0;
}
}
}
if (rowFlag){
for (int i = 0; i < matrix[0].length; i++) {
matrix[0][i] = 0;
}
}
if (colFlag){
for (int i = 0; i < matrix.length; i++) {
matrix[i][0] = 0;
}
}
}
}