/**
* @param A: a sparse matrix
* @param B: a sparse matrix
* @return: the result of A * B
*/
public int[][] multiply(int[][] A, int[][] B) {
if (A == null || B == null) {
return null;
}
int n = A.length;
int m = B[0].length;
int[][] res = new int[n][m];
List<List<Integer>> nonZeroB = new ArrayList<>();
for (int i = 0; i < B.length; i++) {
nonZeroB.add(new ArrayList<>());
for (int j = 0; j < m; j++) {
if (B[i][j] != 0) {
nonZeroB.get(i).add(j);
}
}
}
for (int i = 0; i < A.length; i++) {
for (int k = 0; k < A[0].length; k++) {
if (A[i][k] == 0) {
continue;
}
for (Integer j : nonZeroB.get(k)) {
res[i][j] += A[i][k] * B[k][j];
}
}
}
return res;
}
public int[][] multiply(int[][] A, int[][] B) {
if (A == null && B == null) {
return null;
}
int n = A.length;
int m = B[0].length;
int[][] result = new int[n][m];
for (int i = 0; i < n; i++) {
for (int k = 0; k < A[0].length; k++) { // pull this loop out to check 0 earlier
if (A[i][k] == 0) {
continue;
}
for (int j = 0; j < m; j++) {
if (B[k][j] == 0) { // 其实这一步每次只优化了一句话,所以没什么鸟用
continue;
}
result[i][j] += A[i][k] * B[k][j];
}
}
}
return result;
}
很慢的:
public int[][] multiply(int[][] A, int[][] B) {
if (A == null && B == null) {
return null;
}
int n = A.length;
int m = B[0].length;
int[][] result = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
for (int k = 0; k < A[0].length; k++) {
if (A[i][k] == 0 || B[k][j] == 0) {
continue;
}
result[i][j] += A[i][k] * B[k][j];
}
}
}
return result;
}