Simple 40 ms solution in C++


  • 0
    T
    vector<vector<int>> multiply(vector<vector<int>>& A, vector<vector<int>>& B) {
        int aR = A.size();
        int aC = A[0].size();
    
        int bR =  B.size();
        int bC = B[0].size();
        
        vector<bool> Ab(aR,false);
        
        vector<bool> Bb(bC,false);
        
        for (int i = 0; i <aR; i++)
        {
            int j = 0;
            for (; j<aC; j++)
                if (A[i][j])
                {
                    Ab[i] = true;
                    break;
                }
        }
    
    
        for (int i = 0; i <bC; i++)
        {
            int j = 0;
            for (; j<bR; j++)
                if (B[j][i])
                {
                    Bb[i] = true;
                    break;
                }
        }
        
        
        vector<vector<int>> res(aR, vector<int>(bC,0));
        
        for (int i = 0; i <aR; i++)
        {
            if (!Ab[i]) continue;
            for (int j = 0; j <bC; j++)
            {
                if (!Bb[j]) continue;
                for (int p = 0; p<bR; p++)
                    res[i][j]+=A[i][p]*B[p][j];
            }
        }    
        return res;
    }

Log in to reply
 

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