给定两个 稀疏矩阵 :大小为 m x k 的稀疏矩阵 mat1 和大小为 k x n 的稀疏矩阵 mat2 ,返回 mat1 x mat2 的结果。你可以假设乘法总是可能的。
示例 1:
输入:mat1 = [[1,0,0],[-1,0,3]], mat2 = [[7,0,0],[0,0,0],[0,0,1]]
输出:[[7,0,0],[-7,0,3]]
示例 2:
输入:mat1 = [[0]], mat2 = [[0]]
输出:[[0]]
提示:
m == mat1.length
k == mat1[i].length == mat2.length
n == mat2[i].length
1 <= m, n, k <= 100
-100 <= mat1[i][j], mat2[i][j] <= 100
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/sparse-matrix-multiplication
方法一:模拟
C++提交内容:
class Solution
{
public:
vector<vector<int>> multiply(vector<vector<int>>& mat1, vector<vector<int>>& mat2)
{
int r1 = mat1.size(), r2 = mat2.size();
if (r1 == 0 || r2 == 0)
return vector<vector<int>>{};
int c1 = mat1[0].size(), c2 = mat2[0].size();
vector<vector<int>> res(r1, vector<int>(c2, 0));
for (int r = 0; r < r1; r ++)
{
for (int c = 0; c < c2; c ++)
{
for (int j = 0; j < c1; j ++)
{
res[r][c] += (mat1[r][j] * mat2[j][c]);
}
}
}
return res;
}
};