311. Sparse Matrix Multiplication

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 |

Solution1:利用线性叠加的 Regular 方法

思路: 利用矩阵相乘 的 行的线性叠加,可参考:http://www.jianshu.com/p/11d373b4f6be 中第三个

Time Complexity: O(n * m * nB) Space Complexity: O(1) (avg取决于sparse程度)
行列数:mn * nnB

Solution2:线性叠加形式 + Sparse 方式

思路:计算思路和Solution1相同,但是是先建好sparse的表示,
A sparse matrix can be represented as a sequence of rows, each of which is a sequence of (column-number, value) pairs of the nonzero values in the row.
再一起计算。
(其实一样的,因为solution1中是0也break了;Solution2这样写就是分开步骤了)
参考:http://www.cs.cmu.edu/~scandal/cacm/node9.html
Time Complexity: O(n * m * nB) Space Complexity: O(m *n) (avg取决于sparse程度)

Solution1 Code:

// A: m * n,  B: n * nB,  C: m * nB
public class Solution {
    public int[][] multiply(int[][] A, int[][] B) {
        int m = A.length,n = A[0].length, nB = B[0].length;
        int[][] C = new int[m][nB];

        for(int i = 0; i < m; i++) {
            for(int k = 0; k < n; k++) {
                if (A[i][k] != 0) {
                    for (int j = 0; j < nB; j++) {
                        if (B[k][j] != 0) C[i][j] += A[i][k] * B[k][j];
                    }
                }
            }
        }
        return C;   
    }
}

Solution2 Code:

public class Solution {
    public int[][] multiply(int[][] A, int[][] B) {
        int m = A.length, n = A[0].length, nB = B[0].length;
        int[][] result = new int[m][nB];

        // representation indexA build
        List[] indexA = new List[m];
        for(int i = 0; i < m; i++) {
            List numsA = new ArrayList<>();
            for(int k = 0; k < n; k++) {
                if(A[i][k] != 0){
                    numsA.add(k); 
                    numsA.add(A[i][k]);
                }
            }
            indexA[i] = numsA;
        }
        
        // linear combination of rows
        for(int i = 0; i < m; i++) {
            List numsA = indexA[i];
            for(int p = 0; p < numsA.size() - 1; p += 2) {
                int colA = numsA.get(p);
                int valA = numsA.get(p + 1);
                for(int j = 0; j < nB; j ++) {
                    int valB = B[colA][j];
                    result[i][j] += valA * valB;
                }
            } 
        }

        return result;   
    }
}

你可能感兴趣的:(311. Sparse Matrix Multiplication)