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 |
思路1:矩阵相乘就是所有的k,A(i,k) * B(k,j) = C(i,j) ,稀疏矩阵就是 有很多0,为了提高速度也就是如果 A(i,k) 或者B(k,j), k 从0到length,如果有0,那么这个计算就不进行了。(那么我们来看结果矩阵中的某个元素C[i][j]是怎么来的,起始是A[i][0]*B[0][j] + A[i][1]*B[1][j] + ... + A[i][k]*B[k][j],那么为了不重复计算0乘0,我们首先遍历A数组,要确保A[i][k]不为0,才继续计算,然后我们遍历B矩阵的第k行,如果B[K][J]不为0,我们累加结果矩阵res[i][j] += A[i][k] * B[k][j]; 这样我们就能高效的算出稀疏矩阵的乘法)
class Solution {
public int[][] multiply(int[][] mat1, int[][] mat2) {
// m * k , k * n = m * n;
int m = mat1.length;
int n = mat2[0].length;
int[][] res = new int[m][n];
for(int i = 0; i < m; i++) {
for(int k = 0; k < mat1[0].length; k++) {
if(mat1[i][k] != 0) {
for(int j = 0; j < n; j++) {
if(mat2[k][j] != 0) {
// // m * k , k * n = m * n;
// k是一个list,所以res是个加和的关系;
res[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
}
}
return res;
}
}
思路2:就是稀疏矩阵的表达方式就是记录所有不为0的元素的位置,然后再进行计算。我刚开始想到用hashmap,但是iterator不好用,其实后来看了别人的答案,觉得自己笨了,其实list就够了,只要判断前后相等的元素进行运算就行了。按道理来说,这个应该更快,如果矩阵很大的话;但是这个是150ms的运算速度。上面那个是60ms。
public class Solution {
class Node{
int x;
int y;
public Node(int x, int y){
this.x = x;
this.y = y;
}
}
public int[][] multiply(int[][] A, int[][] B) {
int[][] C = new int[A.length][B[0].length];
List<Node> listA = new ArrayList<Node>();
List<Node> listB = new ArrayList<Node>();
for(int i=0; i<A.length; i++){
for(int j=0; j<A[0].length; j++){
if(A[i][j]!=0){
listA.add(new Node(i,j));
}
}
}
for(int i=0; i<B.length; i++){
for(int j=0; j<B[0].length; j++){
if(B[i][j]!=0){
listB.add(new Node(i,j));
}
}
}
for(Node a: listA){
for(Node b: listB){
if(a.y == b.x){
C[a.x][b.y] += A[a.x][a.y]*B[b.x][b.y];
}
}
}
return C;
}
}