311. Sparse Matrix Multiplicatio

2017-08-21  本文已影响0人  Jeanz

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 |

一刷
题解:已经强调了是sparse matrices, 于是要考虑用其他的方法

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.

例如A的第0行第0列的value为1, 那么A[0] = {0, 1};
A的第1行第0列的value为-1,第2列的value为3, 那么A[1] = {0, -1, 2, 3};

然后把A中的一个个数字取出来,求解。

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];

    List[] indexA = new List[m];
    for(int i = 0; i < m; i++) {
        List<Integer> numsA = new ArrayList<>();
        for(int j = 0; j < n; j++) {
            if(A[i][j] != 0){
                numsA.add(j); 
                numsA.add(A[i][j]);
            }
        }
        indexA[i] = numsA;
    }

    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;   
}
}
上一篇下一篇

猜你喜欢

热点阅读