Sparse Matrix Multiplication

FB高频题
sparse matrix指的是很多value都是0,
1,save the non zero index in pair
2,计算只对非0 index算
新的datastructure-pair<int,int>

class Solution {

public:
    /**
     * @param A: a sparse matrix
     * @param B: a sparse matrix
     * @return: the result of A * B
     */
    vector<vector<int>> multiply(vector<vector<int>> &A, vector<vector<int>> &B) {
        vector<vector<int>>res(A.size(), vector<int>(B[0].size(), 0));

        vector<pair<int,int>>AN, BN;
        for(int i = 0; i < A.size(); i++)
        {
            for(int j = 0; j < A[0].size(); j++)
            {
                if(A[i][j])
                {
                    AN.push_back({i,j});
                }
            }
        }
        
        for(int i = 0; i < B.size(); i++)
        {
            for(int j = 0; j < B[0].size(); j++)
            {
                if(B[i][j])
                {
                    BN.push_back({i,j});
                }
            }
        }
        
        for(auto a : AN)
        {
            for(auto b : BN)
            {
                if(a.second == b.first)
                {
                    res[a.first][b.second] += (A[a.first][a.second] * B[b.first][b.second]);
                }
            }
        }
        
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43476349/article/details/83786424
今日推荐