Skip to content

Commit 5026f72

Browse files
committed
fda
1 parent 1bfa4c8 commit 5026f72

3 files changed

Lines changed: 46 additions & 1 deletion

File tree

‎Leetcodes.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
所有题目列表
22
------
33

4-
## [**283. Move Zeroes**](https://github.com/dingjikerbo/leetcode/tree/master/Solutions/Java/283_Move_Zeroes.md)
4+
## [**283. Move Zeroes**](https://github.com/dingjikerbo/leetcode/tree/master/Solutions/Java/283. Move Zeroes.md)
5+
## [**311. Sparse Matrix Multiplication**](https://github.com/dingjikerbo/leetcode/tree/master/Solutions/Java/311. Sparse Matrix Multiplication.md)
File renamed without changes.
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# [311. Sparse Matrix Multiplication](https://leetcode.com/problems/sparse-matrix-multiplication/)
2+
3+
4+
```
5+
public int[][] multiply(int[][] A, int[][] B) {
6+
int[][] C = new int[A.length][B[0].length];
7+
8+
for (int i = 0; i < C.length; i++) {
9+
for (int j = 0; j < C[0].length; j++) {
10+
for (int k = 0; k < B.length; k++) {
11+
C[i][j] += A[i][k] * B[k][j];
12+
}
13+
}
14+
}
15+
16+
return C;
17+
}
18+
```
19+
20+
`
21+
但是这种写法超时了,看discuss上的优化解法如下,这题核心就是给for循环的内层和外层交换了一下顺序,这样当A[i][j]为零时,下面的for循环就不用走了。我们注意到最里层的for循环有一个常量A[i][j]是不依赖k的,这是核心。虽然交换了for循环,但是C[][]的每个数算法依然没变,仍然是求和。
22+
`
23+
24+
```
25+
public int[][] multiply(int[][] A, int[][] B) {
26+
int M = A.length, T = B.length, N = B[0].length;
27+
28+
int[][] C = new int[M][N];
29+
30+
for (int i = 0; i < M; i++) {
31+
for (int j = 0; j < T; j++) {
32+
if (A[i][j] != 0) {
33+
for (int k = 0; k < N; k++) {
34+
if (B[j][k] != 0) {
35+
C[i][k] += A[i][j] * B[j][k];
36+
}
37+
}
38+
}
39+
}
40+
}
41+
42+
return C;
43+
}
44+
```

0 commit comments

Comments
 (0)