[LeetCode] 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 |

给2个稀疏矩阵,返回矩阵相乘的结果。

在数值分析中,稀疏矩阵(Sparse matrix),是其元素大部分为零的矩阵。反之,如果大部分元素都非零,则这个矩阵是稠密的。在科学与工程领域中求解线性模型时经常出现大型的稀疏矩阵。在使用计算机存储和操作稀疏矩阵时,经常需要修改标准算法以利用矩阵的稀疏结构。由于其自身的稀疏特性,通过压缩可以大大节省稀疏矩阵的内存代价。更为重要的是,由于过大的尺寸,标准的算法经常无法操作这些稀疏矩阵。

解法:稀疏矩阵中绝大多数的元素为0,而相乘的结果是还应该是稀疏矩阵,即还是大多数元素为0,用传统矩阵相乘的算法肯定会处理大量的0乘0的无用功,所以需要适当的优化算法,使其可以顺利通过OJ。一个 i x k 的矩阵A乘以一个 k x j 的矩阵B会得到一个 i x j 大小的矩阵C,矩阵中的某个元素C[i][j]是A[i][0]*B[0][j] + A[i][1]*B[1][j] + ... + A[i][k]*B[k][j],为了不重复计算0乘0,遍历A, B数组, 如果A[i][k], B[K][J]不为0,才继续计算,累加结果res[i][j] += A[i][k] * B[k][j]。

Java: naive solution. T: O(n^3)

public int[][] multiply(int[][] A, int[][] B) {
    //validity check
    int[][] C = new int[A.length][B[0].length];

    for(int i=0; i<C.length; i++){
        for(int j=0; j<C[0].length; j++){
            int sum=0;
            for(int k=0; k<A[0].length; k++){
                sum += A[i][k]*B[k][j];
            }
            C[i][j] = sum;
        }
    }

    return C;
}

Java:

public int[][] multiply(int[][] A, int[][] B) {
    //validity check
    int[][] C = new int[A.length][B[0].length];

    for(int i=0; i<C.length; i++){
        for(int k=0; k<A[0].length; k++){
            if(A[i][k]!=0){
                for(int j=0; j<C[0].length; j++){
                    C[i][j] += A[i][k]*B[k][j];
                }
            }
        }
    }

    return C;
}

Python: optimized, T: O(n^2)

# Time:  O(m * n * l), A is m x n matrix, B is n x l matrix
# Space: O(m * l)
class Solution(object):
    def multiply(self, A, B):
        """
        :type A: List[List[int]]
        :type B: List[List[int]]
        :rtype: List[List[int]]
        """
        m, n, l = len(A), len(A[0]), len(B[0])
        res = [[0 for _ in xrange(l)] for _ in xrange(m)]
        for i in xrange(m):
            for k in xrange(n):
                if A[i][k]:
                    for j in xrange(l):
                        res[i][j] += A[i][k] * B[k][j]
        return res  

C++:

class Solution {
public:
    vector<vector<int>> multiply(vector<vector<int>>& A, vector<vector<int>>& B) {
        vector<vector<int>> res(A.size(), vector<int>(B[0].size()));
        for (int i = 0; i < A.size(); ++i) {
            for (int k = 0; k < A[0].size(); ++k) {
                if (A[i][k] != 0) {
                    for (int j = 0; j < B[0].size(); ++j) {
                        if (B[k][j] != 0) res[i][j] += A[i][k] * B[k][j];
                    }
                }
            }
        }
        return res;
    }
};

C++:

class Solution {
public:
    vector<vector<int>> multiply(vector<vector<int>>& A, vector<vector<int>>& B) {
        vector<vector<int>> res(A.size(), vector<int>(B[0].size()));
        vector<vector<pair<int, int>>> v(A.size(), vector<pair<int,int>>());
        for (int i = 0; i < A.size(); ++i) {
            for (int k = 0; k < A[i].size(); ++k) {
                if (A[i][k] != 0) v[i].push_back({k, A[i][k]});
            }
        }
        for (int i = 0; i < A.size(); ++i) {
            for (int k = 0; k < v[i].size(); ++k) {
                int col = v[i][k].first;
                int val = v[i][k].second;
                for (int j = 0; j < B[0].size(); ++j) {
                    res[i][j] += val * B[col][j];
                }
            }
        }
        return res;
    }
};

  

  

原文地址:https://www.cnblogs.com/lightwindy/p/9692836.html

时间: 2024-10-09 17:26:44

[LeetCode] 311. Sparse Matrix Multiplication 稀疏矩阵相乘的相关文章

[LeetCode] 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 = | -

Leetcode 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 = | -

311. Sparse Matrix Multiplication

/* * 311. Sparse Matrix Multiplication * 2016-7-4 by Mingyang * 这个题目真的是脑壳进屎了才会用HashMap做..... */ 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++

311. Sparse Matrix Multiplication - Medium

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: Input: A = [ [ 1, 0, 0], [-1, 0, 3] ] B = [ [ 7, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 1 ] ] Output: | 1 0 0 | | 7 0 0 | | 7

facebook 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 = | -

HDU 4920 Matrix multiplication 矩阵相乘。稀疏矩阵

Matrix multiplication Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 1775    Accepted Submission(s): 796 Problem Description Given two matrices A and B of size n×n, find the product of them.

HDU 4920 Matrix multiplication(矩阵相乘)

各种TEL,233啊.没想到是处理掉0的情况就可以过啊.一直以为会有极端数据.没想到竟然是这样的啊..在网上看到了一个AC的神奇的代码,经典的矩阵乘法,只不过把最内层的枚举,移到外面就过了啊...有点不理解啊,复杂度不是一样的吗.. Matrix multiplication Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others) Total Submission(s): 640 

Leetcode: 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 = | -

ACdream 1213 Matrix Multiplication(矩阵相乘)

Matrix Multiplication Time Limit: 2000/1000MS (Java/Others) Memory Limit: 128000/64000KB (Java/Others) Submit Statistic Next Problem Problem Description Let us consider undirected graph G = {V; E} which has N vertices and M edges. Incidence matrix of