力扣(LeetCode)算法_C++——稀疏矩阵的乘法

给定两个 稀疏矩阵 :大小为 m x k 的稀疏矩阵 mat1 和大小为 k x n 的稀疏矩阵 mat2 ,返回 mat1 x mat2 的结果。你可以假设乘法总是可能的。

示例 1:

输入:mat1 = [[1,0,0],[-1,0,3]], mat2 = [[7,0,0],[0,0,0],[0,0,1]]

输出:[[7,0,0],[-7,0,3]]

示例 2:

输入:mat1 = [[0]], mat2 = [[0]]

输出:[[0]]

cpp 复制代码
    vector<vector<int>> multiply(vector<vector<int>>& mat1, vector<vector<int>>& mat2) {
        int m = mat1.size();
        int k = mat1[0].size();
        int n = mat2[0].size();
        unordered_map<int, list<pair<int, int>>> map1;
        unordered_map<int, list<pair<int, int>>> map2;
        
        for (int i {0}; i < m; i++) {
            for (int j {0}; j < k; j++) {
                if (mat1[i][j] != 0) map1[mat1[i][j]].push_back(make_pair(i, j));
            }
        }        
        
        for (int i = 0; i < k; i++) {
            for (int j = 0; j < n; j++) {
                if (mat2[i][j] != 0) map2[mat2[i][j]].push_back(make_pair(i, j));
            }
        }

        vector<vector<int>> res(m, vector<int>(n, 0));
        if (m == 0 || n == 0) return res;

        for (auto& element1 : map1) {
            for (auto& list_node1 : element1.second) {
                for (auto& element2 : map2) {
                    for (auto& list_node2 : element2.second) {
                        if (list_node1.second == list_node2.first) {
                            res[list_node1.first][list_node2.second] += element1.first * element2.first;
                        }
                    }
                }
            }
            
        }

        return res;
    }
相关推荐
AA陈超38 分钟前
虚幻引擎5 GAS开发俯视角RPG游戏 P05-08 UI 部件数据表
c++·游戏·ue5·游戏引擎·虚幻
纵有疾風起2 小时前
C++——类和对象(3)
开发语言·c++·经验分享·开源
丁浩6663 小时前
Python机器学习---2.算法:逻辑回归
python·算法·机器学习
承渊政道3 小时前
动态内存管理
c语言·c++·经验分享·c#·visual studio
孤独得猿3 小时前
聊天室项目开发——etcd的安装和使用
linux·服务器·c++·etcd
伏小白白白3 小时前
【论文精度-2】求解车辆路径问题的神经组合优化算法:综合展望(Yubin Xiao,2025)
人工智能·算法·机器学习
new coder3 小时前
[c++语法学习]Day10:c++引用
开发语言·c++·学习
无敌最俊朗@4 小时前
数组-力扣hot56-合并区间
数据结构·算法·leetcode
囚生CY4 小时前
【速写】优化的深度与广度(Adam & Moun)
人工智能·python·算法
哼?~4 小时前
C++11标准 上 (万字解析)
开发语言·c++