forked from havanagrawal/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_311.java
50 lines (42 loc) · 1.09 KB
/
_311.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.fishercoder.solutions;
/**
* 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:
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 class _311 {
public static class Solution1 {
public int[][] multiply(int[][] A, int[][] B) {
int m = A.length;
int n = A[0].length;
int p = B[0].length;
int[][] C = new int[m][p];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (A[i][j] != 0) {
for (int k = 0; k < p; k++) {
if (B[j][k] != 0) {
C[i][k] += A[i][j] * B[j][k];
}
}
}
}
}
return C;
}
}
}