[leetcode]311. Sparse Matrix Multiplication 稀疏矩陣相乘
阿新 • • 發佈:2018-11-25
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:
Input: A = [ [ 1, 0, 0], [-1, 0, 3] ] B = [ [ 7, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 1 ] ] Output: | 1 0 0 | | 7 0 0 | | 7 0 0 | AB= | -1 0 3 | x | 0 0 0 | = | -7 0 3 | | 0 0 1 |
注意:
搞清楚何謂matrix multiply:
一定要有A column 等於B row的特性才能進行matrix multiply
| 1 0 0 | | 7 0 0 | | 7 0 0 | // 1*7 + 0*0 + 0*0 = 7 AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 | | 0 0 1 |
| 1 0 0 | | 7 0 0 | | 7 00 | // 1*0 + 0*0 + 0*0 = 0 AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 | | 0 0 1 |
| 1 0 0 | | 7 0 0 | | 7 0 0 | // 1*0 + 0*0 + 0*1 = 0 AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 | | 0 0 1 |
| 1 0 0 | | 7 0 0 | | 7 0 0 | AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 | // -1*7 + 0*0 + 3*0 = -7| 0 0 1 |
思路:
Brute Force: create product 2D matrix, iterate through it and calculate result for each position
Optimized: Use the information that matrix is sparse. Iterate through A and add the contribution of each number to the result matrix. If A[i][j] == 0, skip the calculation
程式碼:
1 class Solution { 2 public int[][] multiply(int[][] A, int[][] B) { 3 int m = A.length, n = A[0].length; 4 int nB = B[0].length; 5 int [][] res = new int[m][nB]; 6 7 for(int i = 0; i< m; i++){ 8 for(int k = 0; k < n; k++){ 9 if(A[i][k]!=0){ // use Sparse Matrix attributes 10 for(int j = 0; j < nB; j++){ 11 if(B[k][j]!=0) res[i][j] += A[i][k] *B[k][j]; 12 } 13 } 14 } 15 } 16 return res; 17 } 18 }