Fast C++ solution using set<int>


  • 0
    S

    Here is my solution in C++, which is pretty straight-forward.

    class Solution {
    public:
        void setZeroes(vector<vector<int>>& matrix) {
            if(matrix.size() == 0) return;
            if(matrix[0].size() == 0) return;
            set<int> row, col;
            for(int i = 0; i < matrix.size(); ++i){
                for(int j = 0; j < matrix[0].size(); ++j){
                    if(matrix[i][j] == 0){
                        row.insert(i);
                        col.insert(j);
                    }
                }
            }
            for(auto item: row){
                for(int x = 0; x < matrix[0].size(); x++){
                    matrix[item][x] = 0;
                }
            }
            for(auto item: col){
                for(int y = 0; y < matrix.size(); y++){
                    matrix[y][item] = 0;
                }
            }
        }
    };

  • 2
    N

    Your solution is O(m+n) space, is it? Do you have better idea?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.