---
# System prepended metadata

title: 0311. Sparse Matrix Multiplication
tags: [Leetcode, Linear Algebra, Medium]

---

# 0311. Sparse Matrix Multiplication
###### tags: `Leetcode`  `Medium` `Linear Algebra`
Link: https://leetcode.com/problems/sparse-matrix-multiplication/
## 思路
用linear combination的想法简化 就不需要判断每次都判断两个要相乘的element是否为0
![](https://i.imgur.com/woqAGDn.png)

## Code
```java=
class Solution {
    public int[][] multiply(int[][] mat1, int[][] mat2) {
        int[][] res = new int[mat1.length][mat2[0].length];
        
        for(int i = 0;i < mat1.length;i++){
            Arrays.fill(res[i],0);
        }
        
        for(int i = 0;i < mat2.length;i++){
            for(int j = 0;j < mat2[0].length;j++){
                if(mat2[i][j]!=0){
                    for(int k = 0;k < mat1.length;k++){
                        res[k][j]+=mat2[i][j]*mat1[k][i];
                    }
                }
                
            }
        }
        return res;
    }
}
```