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.O(mkn)复杂度。三重for循环直接做。
2.O(mk + nk)复杂度。Map<Integer, List<Integer>>或者List<List<Integer>>来辅助做。存储B矩阵里面非0数的横纵坐标B[k][j]信息。之后遍历A矩阵,入股遇到非0数A[i][k],用存储的信息做一次for循环。非0数A[i][k]就是最后能做贡献的数,它最后会和所有共享k的B[k][...]的数一起做贡献,具体和B[k][j]数就是贡献到result[i][j]的位置。
1.O(mkn)复杂度
class Solution { public int[][] multiply(int[][] A, int[][] B) { if (A == null || B == null || A.length == 0 || A[0].length == 0 || B[0].length == 0) { return new int[0][0]; } int m = A.length; int c = A[0].length; int n = B[0].length; int[][] result = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { int sum = 0; for (int k = 0; k < c; k++) { sum += A[i][k] * B[k][j]; } result[i][j] = sum; } } return result; } }
2.O(mk+nk)复杂度。
class Solution { public int[][] multiply(int[][] A, int[][] B) { if (A == null || B == null || A.length == 0 || A[0].length == 0 || B[0].length == 0) { return new int[0][0]; } int m = A.length; int t = A[0].length; int n = B[0].length; int[][] result = new int[m][n]; Map<Integer, List<Integer>> idxB = new HashMap<>(); for (int k = 0; k < t; k++) { idxB.put(k, new ArrayList<Integer>()); for (int j = 0; j < n; j++) { if (B[k][j] != 0) { idxB.get(k).add(j); } } } for (int i = 0; i < m; i++) { for (int k = 0; k < t; k++) { if (A[i][k] == 0) { continue; } for (int j : idxB.get(k)) { result[i][j] += A[i][k] * B[k][j]; } } } return result; } }