# [LeetCode] 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;
}
};

|
28天前
|

70 1
|
1月前
|

107 0
|
4月前
uva442 Matrix Chain Multiplication
uva442 Matrix Chain Multiplication
12 0
|
12月前
|

UVA442 矩阵链乘 Matrix Chain Multiplication
UVA442 矩阵链乘 Matrix Chain Multiplication
42 0
|

1305 Pairwise Sum and Divide
1305 Pairwise Sum and Divide 题目来源： HackerRank 基准时间限制：1 秒 空间限制：131072 KB 分值: 5 难度：1级算法题 有这样一段程序，fun会对整数数组A进行求值，其中Floor表示向下取整：   fun(A)     sum = 0     for i = 1 to A.
780 0
[LeetCode] Sparse Matrix Multiplication
Problem Description: 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.
978 0