xinyu04

导航

LeetCode 73 Set Matrix Zeroes 思维

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.

Solution

做法并不难,但如果考虑常数空间复杂度的限制,我们只需要记录所在的 \(row,col\) 即可

点击查看代码
class Solution {
private:
    set<int> rows;
    set<int> cols;
    
    bool check_row(set<int> rows, int r){
        if(rows.find(r)!=rows.end())return true;
        return false;
    }
    
    bool check_col(set<int> cols, int c){
        if(cols.find(c)!=cols.end())return true;
        return false;
    }
    
public:
    void setZeroes(vector<vector<int>>& matrix) {
        int r = matrix.size(), c = matrix[0].size();
        for(int i=0;i<r;i++){
            for(int j=0;j<c;j++){
                if(matrix[i][j]==0){rows.insert(i);cols.insert(j);}
            }
        }
        
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++){
                if(check_row(rows,i)||check_col(cols,j))
                    matrix[i][j]=0;
            }
        

    }
};

posted on 2022-07-22 06:15  Blackzxy  阅读(13)  评论(0编辑  收藏  举报