-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathSparseMatrixMultiplication311.java
67 lines (60 loc) · 1.46 KB
/
SparseMatrixMultiplication311.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* 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 SparseMatrixMultiplication311 {
// brutal force
// public int[][] multiply(int[][] A, int[][] B) {
// int ax = A.length;
// int by = B[0].length;
// int len = B.length;
// int[][] res = new int[ax][by];
//
// for (int i=0; i<ax; i++) {
// for (int j=0; j<by; j++) {
// for (int k=0; k<len; k++) {
// res[i][j] += A[i][k] * B[k][j];
// }
// }
// }
//
// return res;
// }
// change order, add zero check
public int[][] multiply(int[][] A, int[][] B) {
int ax = A.length;
int by = B[0].length;
int len = B.length;
int[][] res = new int[ax][by];
for (int i=0; i<ax; i++) {
for (int k=0; k<len; k++) {
if (A[i][k] == 0) continue;
for (int j=0; j<by; j++) {
if (B[k][j] == 0) continue;
res[i][j] += A[i][k] * B[k][j];
}
}
}
return res;
}
}