Thursday, May 5, 2016

LeetCode Q311: 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 |

Solution: Use to arrays of array to store only non-zero elements of A row-wisely and non-zero elements of B col-wisely. However, the test cases of this question in Leetcode is too weak that even the normal math solution is much faster than the answers in the below.

No comments:

Post a Comment