难度: Medium
原题连接
内容描述
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:
Input:
A = [
[ 1, 0, 0],
[-1, 0, 3]
]
B = [
[ 7, 0, 0 ],
[ 0, 0, 0 ],
[ 0, 0, 1 ]
]
Output:
| 1 0 0 | | 7 0 0 | | 7 0 0 |
AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
| 0 0 1 |
思路 1
直接搞一个完全的稀疏矩阵然后一个一个地去看,这样万一内存不够怎么办,所以我们基于A建一个非0的新list,然后对应的求出结果,这样操作数会少一些,
并且对内存的要求也没有那么高,借用一句话I think, in perspective of Big4, they would have a HUGE sparse dataset. And would like to process them in a machine. So memory does not fit without the Table representation of sparse matrix. And this is efficient since can be loaded into a one machine
class Solution(object):
def multiply(self, A, B):
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
"""
m, n, nB = len(A), len(A[0]), len(B[0])
res = [[0] * nB for i in range(m)]
idxA = []
for i in range(len(A)):
tmp = []
for j in range(len(A[0])):
if A[i][j] != 0:
tmp.append(j)
idxA.append(tmp)
print(idxA)
for i in range(len(idxA)):
for j in idxA[i]:
for k in range(nB):
res[i][k] += A[i][j] * B[j][k]
return res