-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path654.sparse-matrix-multiplication.py
96 lines (86 loc) · 2.15 KB
/
654.sparse-matrix-multiplication.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# Tag: Mathmatics
# Time: O(NMK)
# Space: O(NM)
# Ref: Leetcode-311
# Note: -
# Given two [Sparse Matrix](https://en.wikipedia.org/wiki/Sparse_matrix "Sparse Matrix") A and B, return the result of AB.
#
# You may assume that A's column number is equal to B's row number.
#
# **Example1**
# ```
# Input:
# [[1,0,0],[-1,0,3]]
# [[7,0,0],[0,0,0],[0,0,1]]
# Output:
# [[7,0,0],[-7,0,3]]
# Explanation:
# 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 |
# ```
# **Example2**
# ```
# Input:
# [[1,0],[0,1]]
# [[0,1],[1,0]]
# Output:
# [[0,1],[1,0]]
# ```
#
#
from typing import (
List,
)
class Solution:
"""
@param a: a sparse matrix
@param b: a sparse matrix
@return: the result of A * B
"""
def multiply(self, a: List[List[int]], b: List[List[int]]) -> List[List[int]]:
# write your code here
n = len(a)
k = len(b)
m = len(b[0])
res = [[0] * m for i in range(n)]
for i in range(n):
for j in range(m):
for d in range(k):
res[i][j] += a[i][d] * b[d][j]
return res
class Solution:
"""
@param a: a sparse matrix
@param b: a sparse matrix
@return: the result of A * B
"""
def multiply(self, a: List[List[int]], b: List[List[int]]) -> List[List[int]]:
# write your code here
n = len(a)
m = len(b[0])
sparseB = [[] for i in range(len(b))]
res = [[0] * m for i in range(n)]
for i in range(len(b)):
for j in range(m):
if b[i][j] != 0:
sparseB[i].append((j, b[i][j]))
for i in range(n):
for k in range(len(a[i])):
if a[i][k] == 0:
continue
for j, v in sparseB[k]:
res[i][j] += a[i][k] * v
return res