Leetcode 刷题 - 311 - Sparse Matrix Multiplication

这篇博客介绍了如何解决LeetCode上的311题,即稀疏矩阵的乘法问题。通过利用Python的内置函数zip、map和sum,可以高效地完成矩阵的乘法运算,将两个稀疏矩阵相乘并得到结果。
摘要由CSDN通过智能技术生成

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 |




根据题意,就是线性代数的矩阵乘法。 矩阵乘法, 第i行,j列的数字,是有第一个矩阵的i行,和第二个矩阵的j列相乘,再相加得到的。

利用python的built-in function, zip, map, sum能够很快解题。


class Solution(object):
    def multiply(self, A, B):
        """
        :type A: List[List[int]]
        :type B: List[List[int]]
        :rtype: List[List[int]]
        """
        result = []
        BT = zip(*B) # transfer B,get the column of B
        length = len(B)
        for row in A:
            if not any(row):
                result.append([0] * length)
                continue
            result.append([sum(map(lambda (x, y): x*y, zip(row, col))) 
                                        if any(col) else 0 for col in BT])

        return result
 

主要是zip(*B),首先*表示unpack,把B:List[List[int]]外层的list打开,变成了zip([a,,b,c], [d,e,f], [h,i,j])的样子,直接得到了矩阵的转置,即我们需要的列。

然后就是loop第一个矩阵,做乘法,累加,得到一个新的list,即我们需要的。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值