# 311. Sparse Matrix Multiplication

Given two sparse matrices A and B , return the result of AB.

You may assume that A ‘s column number is equal to B ‘s row number.

Example:

``````**A** = [
[ 1, 0, 0],
[-1, 0, 3]
]

**B** = [
[ 7, 0, 0 ],
[ 0, 0, 0 ],
[ 0, 0, 1 ]
]

|  1 0 0 |   | 7 0 0 |   |  7 0 0 |
**AB** = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
| 0 0 1 |
``````

``````class Solution {
public:
vector<vector<int>> multiply(vector<vector<int>>& A, vector<vector<int>>& B) {
vector<vector<int>> res(A.size(), vector<int>(B[0].size()));
for (int i = 0; i < A.size(); ++i) {
for (int k = 0; k < A[0].size(); ++k) {
if (A[i][k] != 0) {
for (int j = 0; j < B[0].size(); ++j) {
if (B[k][j] != 0) res[i][j] += A[i][k] * B[k][j];
}
}
}
}
return res;
}
};
``````

``````class Solution {
public:
vector<vector<int>> multiply(vector<vector<int>>& A, vector<vector<int>>& B) {
vector<vector<int>> res(A.size(), vector<int>(B[0].size()));
vector<vector<pair<int, int>>> v(A.size(), vector<pair<int,int>>());
for (int i = 0; i < A.size(); ++i) {
for (int k = 0; k < A[i].size(); ++k) {
if (A[i][k] != 0) v[i].push_back({k, A[i][k]});
}
}
for (int i = 0; i < A.size(); ++i) {
for (int k = 0; k < v[i].size(); ++k) {
int col = v[i][k].first;
int val = v[i][k].second;
for (int j = 0; j < B[0].size(); ++j) {
res[i][j] += val * B[col][j];
}
}
}
return res;
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/311

Dot Product of Two Sparse Vectors

https://leetcode.com/problems/sparse-matrix-multiplication/

https://leetcode.com/discuss/77235/ac-soluiton-code

https://leetcode.com/discuss/71912/easiest-java-solution

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation