博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
311. Sparse Matrix Multiplication
阅读量:4561 次
发布时间:2019-06-08

本文共 1912 字,大约阅读时间需要 6 分钟。

题目:

Given two  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 |

链接: 

题解:

Sparse Matrix相乘。题目提示要用HashMap,于是我们就用HashMap, 保存A中不为0行,以及B中不为0的列,然后遍历两个hashmap来更新结果数组。

Time Complexity - O(mnkl),  Space Complexity - O(mn + kl)。

public class Solution {    public int[][] multiply(int[][] A, int[][] B) {        if(A == null || B == null || A.length == 0 || B.length == 0 || (A[0].length != B.length)) {            return new int[][]{};        }                Map
rowInA = new HashMap<>(); // store non-zero rows in A Map
colInB = new HashMap<>(); // store non-zero cols in B for(int i = 0; i < A.length; i++) { for(int j = 0; j < A[0].length; j++) { if(A[i][j] != 0) { rowInA.put(i, A[i]); break; } } } for(int j = 0; j < B[0].length; j++) { for(int i = 0; i < B.length; i++) { if(B[i][j] != 0) { int[] tmp = new int[B.length]; for(int k = 0; k < B.length; k++) { tmp[k] = B[k][j]; } colInB.put(j, tmp); break; } } } int[][] res = new int[A.length][B[0].length]; for(int i : rowInA.keySet()) { for(int j : colInB.keySet()) { for(int k = 0; k < A[0].length; k++) { res[i][j] += rowInA.get(i)[k] * colInB.get(j)[k]; } } } return res; }}

 

Reference:

 

转载于:https://www.cnblogs.com/yrbbest/p/5060667.html

你可能感兴趣的文章
1033. 旧键盘打字(20)
查看>>
The Zen of Python
查看>>
git安装及使用
查看>>
mysql一个非常实用解决sql查询优化的函数explain
查看>>
图文讲解NTFS和FAT32硬盘下 asp.net 生成word 错误: 80070005 和 错误:8000401a 的解决方法...
查看>>
《学习》5连接查询(高级查询)
查看>>
python日常—爬取豆瓣250条电影记录
查看>>
11.3NOIP模拟赛
查看>>
1.SDL介绍
查看>>
【重要更新】语言转换类编程工具Tangible系列本月又更新了!
查看>>
现场赛:开关灯问题
查看>>
codeforces A. Jeff and Rounding (数学公式+贪心)
查看>>
zoj 3462
查看>>
java多线程-信号量
查看>>
如何在Delphi XE2中使用Dynamic Web TWAIN
查看>>
js自定义实用函数总结
查看>>
java内存区域与内存溢出异常
查看>>
点点滴滴的成长[2011-11-1]:理解C#修饰符
查看>>
csrf(跨站请求伪造)
查看>>
高性能MySQL笔记-第1章MySQL Architecture and History-001
查看>>