其他分享
首页 > 其他分享> > LeetCode 73 Set Matrix Zeroes 思维

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;
            }
        

    }
};

标签:Zeroes,Set,return,Matrix,int,cols,set,rows,matrix
来源: https://www.cnblogs.com/xinyu04/p/16504251.html