Wednesday, December 28, 2016

Leetcode/F家,Linkedin -- 311. Sparse Matrix Multiplication

 311. Sparse Matrix Multiplication
  • Difficulty: Medium
https://leetcode.com/problems/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 |

思路:
解法1:正常for loop,最外面 i: A_row,第二层 j : A_col = B_row,第三层 k: B_col
            *new martix form by A'row * B'col
            *lock A, fill C by row(match pos in B row using j: A'col = B'row)比如说A[0,1]会和所有在B row 1的元素相乘。
             *sparse to aviol multiply 0, skip A[] = 0



public class Solution {
    public int[][] multiply(int[][] A, int[][] B) {
        int A_row = A.length;
        int A_col = A[0].length;//B'row
        int B_col = B[0].length;
        int[][] C = new int[A_row][B_col];
        //3 loop, i - Arow, j - Bcol, k - Acol = Brow
        for(int i = 0; i < A_row; i++){
            for(int j = 0; j < A_col; j++){
                if(A[i][j] == 0)continue;//sparse matrix    
                for(int k = 0; k < B_col; k++){
                    C[i][k] += A[i][j] * B[j][k];//A'col = B'row
                }
            }
        }
        return C;
    }
}

No comments:

Post a Comment