leetcode - 311. Sparse Matrix Multiplication

Description

Given two sparse matrices mat1 of size m x k and mat2 of size k x n, return the result of mat1 x mat2. You may assume that multiplication is always possible.

Example 1:
leetcode - 311. Sparse Matrix Multiplication_第1张图片

Input: mat1 = [[1,0,0],[-1,0,3]], mat2 = [[7,0,0],[0,0,0],[0,0,1]]
Output: [[7,0,0],[-7,0,3]]

Example 2:

Input: mat1 = [[0]], mat2 = [[0]]
Output: [[0]]

Constraints:

m == mat1.length
k == mat1[i].length == mat2.length
n == mat2[i].length
1 <= m, n, k <= 100
-100 <= mat1[i][j], mat2[i][j] <= 100

Solution

Simulation

Do a simulation of matrix multiplication

Time complexity: o ( m ∗ n ∗ k ) o(m*n*k) o(mnk)
Space complexity: o ( m ∗ n ) o(m*n) o(mn)

Compressed Matrix

Since the matrix is sparse, we could use a map to store the non-zero positions and values.

Code

Simulation

class Solution:
    def multiply(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]:
        m, k = len(mat1), len(mat1[0])
        k, n = len(mat2), len(mat2[0])
        res = [[0] * n for _ in range(m)]
        for i in range(m):
            for j in range(n):
                for index in range(k):
                    res[i][j] += mat1[i][index] * mat2[index][j]
        return res

你可能感兴趣的:(OJ题目记录,leetcode,算法,职场和发展)