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.itdecent.cn/p/11d373b4f6be 中第三個(gè)

Time Complexity: O(n * m * nB) Space Complexity: O(1) (avg取決于sparse程度)
行列數(shù):mn * nnB

Solution2:線性疊加形式 + Sparse 方式

思路:計(jì)算思路和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.
再一起計(jì)算。
(其實(shí)一樣的,因?yàn)閟olution1中是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<Integer> 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<Integer> 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;   
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容