Given two sparse matrices mat1 of size m x k and mat2 of size k x n, return the result of mat1 x mat2. You may assume that multiplication is always possible.
Example 1:
Input: mat1 = [[1,0,0],[-1,0,3]], mat2 = [[7,0,0],[0,0,0],[0,0,1]]
Output: [[7,0,0],[-7,0,3]]
Example 2:
Input: mat1 = [[0]], mat2 = [[0]]
Output: [[0]]
Constraints:
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
分析
题目大意一目了然,就是matrix multiplication。 输入数组为mat1, mat2, 输出数组为ans. 已知 ans[i][j] = dot product of( mat1 的第i行, mat2的第j列 )。 为了更方便地编程,我先将mat2 transpose成transposed_mat2,然后
ans[i][j] = dot product of( mat1 的第i行, transposed_mat2的第j行)
class Solution(object):
def multiply(self, mat1, mat2):
"""
:type mat1: List[List[int]]![请添加图片描述](https://img-blog.csdnimg.cn/7d56f25971454bbba36c039fd187e4f3.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3poaXJvbmd3YW5nOTQ=,size_16,color_FFFFFF,t_70)
:type mat2: List[List[int]]
:rtype: List[List[int]]
"""
def dot_product(arr1, arr2):
ans = 0
for a1, a2 in zip(arr1, arr2):
ans += a1 * a2
return ans
nRow2, nCol2 = len(mat2), len(mat2[0])
tran_mat2 = [ [ mat2[i][j] for i in range(nRow2) ] for j in range(nCol2) ]
nRow1, nCol1 = len(mat1), len(mat1[0])
ans = [ [ dot_product(mat1[j], tran_mat2[i] ) for i in range(nCol2)] for j in range(nRow1) ]
return ans
2021-08-04 炖了个红酒牛腱, 圣荷西,晴。