File tree 1 file changed +87
-0
lines changed
src/main/java/com/leetcode/arrays
1 file changed +87
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .leetcode .arrays ;
2
+
3
+ import java .util .Arrays ;
4
+
5
+ import static org .junit .jupiter .api .Assertions .assertEquals ;
6
+
7
+ /**
8
+ * Level: Medium
9
+ * Link: https://leetcode.com/problems/sparse-matrix-multiplication/
10
+ * Description:
11
+ * Given two sparse matrices A and B, return the result of AB.
12
+ *
13
+ * You may assume that A's column number is equal to B's row number.
14
+ *
15
+ * Example:
16
+ *
17
+ * Input:
18
+ *
19
+ * A = [
20
+ * [ 1, 0, 0],
21
+ * [-1, 0, 3]
22
+ * ]
23
+ *
24
+ * B = [
25
+ * [ 7, 0, 0 ],
26
+ * [ 0, 0, 0 ],
27
+ * [ 0, 0, 1 ]
28
+ * ]
29
+ *
30
+ * Output:
31
+ *
32
+ * | 1 0 0 | | 7 0 0 | | 7 0 0 |
33
+ * AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
34
+ * | 0 0 1 |
35
+ *
36
+ * @author rampatra
37
+ * @since 2019-08-09
38
+ */
39
+ public class SparseMatrixMultiplication {
40
+
41
+ /**
42
+ * Time Complexity: O(Arow * Acol * Bcol)
43
+ * Space Complexity: O(Arow * Bcol)
44
+ *
45
+ * @param A
46
+ * @param B
47
+ * @return
48
+ */
49
+ public static int [][] multiply (int [][] A , int [][] B ) {
50
+ int [][] AB = new int [A .length ][B [0 ].length ];
51
+
52
+ for (int Bcol = 0 ; Bcol < B [0 ].length ; Bcol ++) {
53
+ for (int Arow = 0 ; Arow < A .length ; Arow ++) {
54
+ int sum = 0 ;
55
+ for (int Acol = 0 ; Acol < A [0 ].length ; Acol ++) {
56
+ sum += A [Arow ][Acol ] * B [Acol ][Bcol ];
57
+ }
58
+ AB [Arow ][Bcol ] = sum ;
59
+ }
60
+ }
61
+
62
+ return AB ;
63
+ }
64
+
65
+ public static void main (String [] args ) {
66
+ assertEquals (Arrays .deepToString (new int [][]{
67
+ {7 , 0 , 0 },
68
+ {-7 , 0 , 3 }
69
+ }), Arrays .deepToString (multiply (new int [][]{
70
+ {1 , 0 , 0 },
71
+ {-1 , 0 , 3 }
72
+ }, new int [][]{
73
+ {7 , 0 , 0 },
74
+ {0 , 0 , 0 },
75
+ {0 , 0 , 1 }
76
+ })));
77
+
78
+ assertEquals (Arrays .deepToString (new int [][]{
79
+ {0 }
80
+ }), Arrays .deepToString (multiply (new int [][]{
81
+ {0 , 1 }
82
+ }, new int [][]{
83
+ {1 },
84
+ {0 }
85
+ })));
86
+ }
87
+ }
You can’t perform that action at this time.
0 commit comments