跳到主要内容

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:

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 |

Constraints:

  • 1 <= A.length, B.length <= 100
  • 1 <= A[i].length, B[i].length <= 100
  • -100 <= A[i][j], B[i][j] <= 100

分析

代码

# Sparse Matrix Multiplication
# Time Complexity: O(m*n*p), Space Complexity: O(1)
def multiply(A: list[list[int]], B: list[list[int]]) -> list[list[int]]:
m, n, p = len(A), len(A[0]), len(B[0])
C = [[0] * p for _ in range(m)]

for i in range(m):
for k in range(n):
if A[i][k] != 0:
for j in range(p):
if B[k][j] != 0:
C[i][j] += A[i][k] * B[k][j]
return C