My hacky straightforward hashtable solution


  • 0
    A
    void setZeroes(vector<vector<int> > &matrix) {
        unordered_set<int> zeroR, zeroC;
        for (int i = 0; i < matrix.size(); i++) {
            for (int j = 0; j < matrix[i].size(); j++) {
                if (matrix[i][j] == 0) {
                    if (zeroR.find(i) == zeroR.end())
                        zeroR.insert(i);
                    if (zeroC.find(j) == zeroC.end())
                        zeroC.insert(j);
                }
            }
        }
        
        for (auto it = zeroR.begin(); it != zeroR.end(); it++) {
            int i = *it;
            for (int j = 0; j < matrix[i].size(); j++) {
                matrix[i][j] = 0;
            }
        }
        
        for (auto it = zeroC.begin(); it != zeroC.end(); it++) {
            int j = *it;
            for (int i = 0; i < matrix.size(); i++) {
                matrix[i][j] = 0;
            }
        }
    }
    

    I think this might be too tricky so in real interview my solution may not be accepted... but I think this is quite straightforward to me although in worst case I need O(m+n) space for storing the hash table itself. The size of the hash table is completely depending on how many zeros.


Log in to reply
 

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