题目地址:https://leetcode-cn.com/problems/sparse-matrix-multiplication/

题目描述

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 |

题目大意

给定两个 稀疏矩阵 A 和 B,请你返回 AB。你可以默认 A 的列数等于 B 的行数。

解题方法

暴力

直接按照矩阵乘法,可以暴力求解。矩阵乘法是三重循环,时间复杂度是O(N^3)。

题目给的系数矩阵的特征怎么用呢?可以考虑先遍历一次两个矩阵,记录下A的行和B的列全部为0的索引,当遍历到这些索引时,直接给res中填入0。下面的代码没有这么做,也能通过。

C++代码如下:

class Solution {
public:
vector<vector<int>> multiply(vector<vector<int>>& A, vector<vector<int>>& B) {
if (A.empty() || A[0].empty() || B.empty() || B[0].empty()) return vector<vector<int>>();
int M = A.size();
int N = B[0].size();
vector<vector<int>> res(M, vector<int>(N, 0));
for (int row = 0; row < M; ++row) {
for (int col = 0; col < N; ++col) {
int cur = 0;
for (int i = 0; i < A[0].size(); ++i) {
cur += A[row][i] * B[i][col];
}
res[row][col] = cur;
}
}
return res;
}
};

科学计算库numpy

Python有科学计算库numpy可以使用,直接使用库函数求得矩阵的乘法。

import numpy as np
class Solution(object):
def multiply(self, A, B):
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
"""
a = np.array(A)
b = np.array(B)
return np.matmul(a, b)

日期

2019 年 9 月 24 日 —— 梦见回到了小学,小学已经芳草萋萋破败不堪

最新文章

  1. 【JUC】JDK1.8源码分析之Semaphore(六)
  2. java中使用jxl导出Excel表格详细通用步骤
  3. Python札记 -- 文件压缩
  4. 如何用RadioButton做一个底部的切换栏
  5. 启用 CORS 来解决这个问题(ajax跨域请求)
  6. 菜鸟学四轴控制器之3:数字积分法DDA实现直线插补
  7. Selenium2Library系列 keywords 之 _SelectElementKeywords 之 list_should_have_no_selections(self, locator)
  8. JavaScript中的事件冒泡机制
  9. 【转】Android 带checkbox的listView 实现多选,全选,反选----解决checkbox错位问题
  10. C#中的多线程-入门
  11. Objective-C和Swift
  12. qq面板(仿版,未完待续中。。。。)---2017-04-24
  13. iOS自定义文字高度添加行间距
  14. 在Python中用Request库模拟登录(三):Discuz论坛(未加密,有验证码,有隐藏验证)
  15. bzoj2437 [Noi2011]兔兔与蛋蛋
  16. vscode1.30.1使用的electron3.0.10中的bug
  17. .net Core 下数据库访问
  18. shell编程基础(二): shell脚本语法之分支语句和循环语句
  19. Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005 拒绝访问
  20. 【Codeforces 1137C】Museums Tour

热门文章

  1. Linux基础——常用命令
  2. Excel-vlookup内部能不能用函数?(即内部嵌套函数)
  3. PDFium 渲染
  4. 5 — springboot中的yml多环境配置
  5. Spark(十)【RDD的读取和保存】
  6. Flume对接Kafka
  7. 初学js正则表达式之密码强度验证
  8. 【swift】Xcode未响应(卡死、卡住、CPU满载、忙碌、转圈圈)
  9. Bootstrap-table动态表格
  10. synchronized底层浅析(一)