My O(1) space solution and 84ms


  • -4
    A
    class Solution {
    public:
        void setZeroes(vector<vector<int>>& matrix) {
            int rows = matrix.size();
            int cols = matrix[0].size();
            vector<pair<int,int>> index;
            pair<int, int> p;
            for(int i=0;i<rows;i++){
                for(int j=0;j<cols;j++){
                    if(matrix[i][j]==0){
                        p=std::make_pair(i,j);
                        index.push_back(p);
                    }
                }
            }
            if(index.size()>0){
                for(int k=0;k<index.size();k++){
                    int r=index[k].first;
                    int c=index[k].second;
                    for(int i=0;i<cols;i++)
                        matrix[r][i]=0;
                    for(int i=0;i<rows;i++)
                        matrix[i][c]=0;
                }
            }
        }
    };

  • 0

    Since there is a vector<pair<int, int>> index and the size of it may reach O(rows * cols) if all the elements of matrix are 0, this solution is not of O(1) now.


  • 0
    D

    I can't agree more with your comment!


Log in to reply
 

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