311. 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:
1 | Input: |
Idea
normally,
1 | for i in range(n): |
In fact, this is same as
1 | for i in range(n): |
In this form, each A[i][k] may multiply a row of B, when a is 0, we can ignore it. What’s more, we can record the indexes of non-zero elements in a row of B, which also fasten the computation.
Code
1 | class Solution(object): |