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 |
--------------------------------------------------------------------------
直接搞大家都會,比較好的方式是把B轉換成列存儲,列中非零的位置再去乘A。
class Solution:
def multiply(self, A, B):
cols = [[(j, b) for j, b in enumerate(col) if b!=0]
for col in zip(*B)]
return [[sum(row[j]*b for j, b in col)
for col in cols]
for row in A]