思路
思路1:常规解法,直接三重循环,按照公式计算。
时间复杂度O(
n
3
n^3
n3), 空间复杂度O(1)
思路2:对A矩阵进行优化,如果值为0, 则不继续循环最内层循环来计算【这里将k循环提到了第二层】
时间复杂度O(
n
2
n^2
n2~
n
3
n^3
n3), 空间复杂度O(1)
思路3:进一步优化,提前将B中值不为0的元素的下标存到一个list中,在最内层的循环里就不需要每一次进行判断是否B为0,而是直接读取不为0的值的下标,在常数项上对时间复杂度进行优化
时间复杂度O(
n
2
n^2
n2~
n
3
n^3
n3), 空间复杂度O(1)
代码
常规法
public class Solution {
/**
* @param A a sparse matrix
* @param B a sparse matrix
* @return the result of A * B
*/
public int[][] multiply(int[][] A, int[][] B) {
// Write your code here
int n = A.length;
int m = B[0].length;
int t = A[0].length;
int[][] C = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
for (int k = 0; k < t; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
return C;
}
}
改进A矩阵
public class Solution {
/**
* @param A a sparse matrix
* @param B a sparse matrix
* @return the result of A * B
*/
public int[][] multiply(int[][] A, int[][] B) {
// Write your code here
int n = A.length;
int m = B[0].length;
int t = A[0].length;
int[][] C = new int[n][m];
for (int i = 0; i < n; i++) {
for (int k = 0; k < t; k++) {
if (A[i][k] == 0) {
continue;
}
for (int j = 0; j < m; j++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
return C;
}
}
进一步改进
public class Solution {
/**
* @param A a sparse matrix
* @param B a sparse matrix
* @return the result of A * B
*/
public int[][] multiply(int[][] A, int[][] B) {
// Write your code here
int n = A.length;
int m = B[0].length;
int t = A[0].length;
int[][] C = new int[n][m];
List<List<Integer>> col = new ArrayList<>();
for (int i = 0; i < t; i++) {
col.add(new ArrayList<>());
for (int j = 0; j < m; j++) {
if (B[i][j] != 0) {
col.get(i).add(j);
}
}
}
for (int i = 0; i < n; i++) {
for (int k = 0; k < t; k++) {
if (A[i][k] == 0) {
continue;
}
for (int j: col.get(k)) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
return C;
}
}