forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSparseMatrixMultiplication.java
87 lines (79 loc) · 1.95 KB
/
SparseMatrixMultiplication.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package com.leetcode.arrays;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Level: Medium
* Link: https://leetcode.com/problems/sparse-matrix-multiplication/
* Description:
* 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 |
*
* @author rampatra
* @since 2019-08-09
*/
public class SparseMatrixMultiplication {
/**
* Time Complexity: O(Arow * Acol * Bcol)
* Space Complexity: O(Arow * Bcol)
*
* @param A
* @param B
* @return
*/
public static int[][] multiply(int[][] A, int[][] B) {
int[][] AB = new int[A.length][B[0].length];
for (int Bcol = 0; Bcol < B[0].length; Bcol++) {
for (int Arow = 0; Arow < A.length; Arow++) {
int sum = 0;
for (int Acol = 0; Acol < A[0].length; Acol++) {
sum += A[Arow][Acol] * B[Acol][Bcol];
}
AB[Arow][Bcol] = sum;
}
}
return AB;
}
public static void main(String[] args) {
assertEquals(Arrays.deepToString(new int[][]{
{7, 0, 0},
{-7, 0, 3}
}), Arrays.deepToString(multiply(new int[][]{
{1, 0, 0},
{-1, 0, 3}
}, new int[][]{
{7, 0, 0},
{0, 0, 0},
{0, 0, 1}
})));
assertEquals(Arrays.deepToString(new int[][]{
{0}
}), Arrays.deepToString(multiply(new int[][]{
{0, 1}
}, new int[][]{
{1},
{0}
})));
}
}