/** * @param A: a sparse matrix * @param B: a sparse matrix * @return: the result of A * B */publicint[][] multiply(int[][] A,int[][] B) {if (A ==null|| B ==null) {returnnull; }int n =A.length;int m =B[0].length;int[][] res =newint[n][m];List<List<Integer>> nonZeroB =newArrayList<>();for (int i =0; i <B.length; i++) {nonZeroB.add(newArrayList<>());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;}
publicint[][] multiply(int[][] A,int[][] B) {if (A ==null&& B ==null) {returnnull; }int n =A.length;int m =B[0].length;int[][] result =newint[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 earlierif (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; }
很慢的:
publicint[][] multiply(int[][] A,int[][] B) {if (A ==null&& B ==null) {returnnull; }int n =A.length;int m =B[0].length;int[][] result =newint[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; }