Created
April 18, 2016 20:58
-
-
Save cangoal/784ab3066b20b57752a1431dbe102d92 to your computer and use it in GitHub Desktop.
LeetCode - Sparse Matrix Multiplication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | | |
public int[][] multiply(int[][] A, int[][] B) { | |
int ma = A.length, na = A[0].length, nb = B[0].length; | |
int[][] res = new int[ma][nb]; | |
for(int i = 0; i < ma; i++){ | |
for(int j = 0; j < na; j++){ | |
if(A[i][j] == 0) continue; | |
for(int k = 0; k < nb; k++){ | |
res[i][k] += A[i][j] * B[j][k]; | |
} | |
} | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment