程序员面试金典——1.7清除行列

Solution1:我的答案

空间复杂度比较高,垃圾算法

class Clearer {
public:
    vector > clearZero(vector > mat, int n) {
        // write code here
        vector > mat_copy = mat;
        if(n == 0) return mat_copy;
        set row_zero, col_zero;
        for(int i = 0; i < mat.size(); i++) {
            for(int j = 0; j < mat[i].size(); j++) {
                if(mat[i][j] == 0) {
                    if(row_zero.find(i) == row_zero.end()) {
                        clearRow(mat_copy, i);
                        row_zero.insert(i);
                    }
                    if(col_zero.find(j) == col_zero.end()) {
                        clearCol(mat_copy, j);
                        col_zero.insert(j);
                    }
                }
            }
        }
        return mat_copy;
    }
    
    void clearRow(vector > &mat, int r) {
        for(int j = 0; j < mat[r].size(); j++) {
            mat[r][j] = 0;
        }
        return;
    }
    
    void clearCol(vector > &mat, int c) {
        for(int i = 0; i < mat.size(); i++) {
            mat[i][c] = 0;
        }
        return;
    }
};

Solution2:

记录下所有含0的行列值,再遍历。代码比较简练,学习之!

class Clearer {
public:
    vector > clearZero(vector > mat, int n) {
        // write code here
        vector row(n, false);
        vector column(n, false);
         
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                if(mat[i][j] == 0){
                    row[i] = true;
                    column[j] = true;
                }
            }
        }
         
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                if(row[i] || column[j]){
                    mat[i][j] = 0;
                }
            }
        }
         
        return mat;
    }
};

你可能感兴趣的:(程序员面试金典题目笔记)