[Swift]LeetCode311. 稀疏矩阵相乘 $ Sparse Matrix Multiplication

[Swift]LeetCode311. 稀疏矩阵相乘 $ Sparse Matrix Multiplication,第1张

概述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 ],

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],[-1,3]]B = [  [ 7,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 |

给定两个稀疏矩阵A和B,返回AB的结果。 

您可以假定A的列号等于B的行号。

例子:

A = [  [ 1,1 ]]     |  1 0 0 |   | 7 0 0 |   |  7 0 0 |AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |                  | 0 0 1 |
Solution:
 1 class Solution { 2     func multiply(_ A:inout [[Int]],_ B:inout [[Int]]) ->[[Int]] { 3         var res:[[Int]] = [[Int]](repeating:[Int](repeating:0,count:B[0].count),count:A.count) 4         for i in 0..<A.count 5         { 6             for k in 0..<A[0].count 7             { 8                 if A[i][k] != 0 9                 {10                     for j in 0..<B[0].count11                     {12                         if B[k][j] != 013                         {14                             res[i][j] += A[i][k] * B[k][j]15                         }16                     }17                 }18             }19         }20         return res            21     }22 }

Solution:

 1 class Solution { 2     func multiply(_ A:inout [[Int]],count:A.count) 4         var v:[[(Int,Int)]] = [[(Int,Int)]](repeating:[(Int,Int)](),count:A.count) 5         for i in 0..<A.count 6         { 7             for k in 0..<A[i].count 8             { 9                 if A[i][k] != 010                 {11                     v[i].append((k,A[i][k]))12                 }13             }14         }15         for i in 0..<A.count16         {17             for k in 0..<v[i].count18             {19                 var col:Int = v[i][k].020                 var val:Int = v[i][k].121                 for j in 0..<B[0].count22                 {23                     res[i][j] += val * B[col][j]24                 }25             }26         }27         return res            28     }29 }

点击:Playground测试

1 var A:[[Int]] = [[ 1,0,0],[-1,3]]2 var B:[[Int]] = [[ 7,0 ],[ 0,1 ]]3 let sol = Solution()4 print(sol.multiply(&A,&B))5 //Print [[7,[-7,3]]
总结

以上是内存溢出为你收集整理的[Swift]LeetCode311. 稀疏矩阵相乘 $ Sparse Matrix Multiplication全部内容,希望文章能够帮你解决[Swift]LeetCode311. 稀疏矩阵相乘 $ Sparse Matrix Multiplication所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1014336.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存