311. Sparse Matrix Multiplication解题报告

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 炖了个红酒牛腱, 圣荷西,晴。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值