Leetcode: Sparse Matrix Multiplication
2015-12-28 11:02
183 查看
Question
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 ]
]
[code] | 1 0 0 | | 7 0 0 | | 7 0 0 |
AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
| 0 0 1 |
Hide Company Tags LinkedIn
Hide Tags Hash Table
My first try
Time complexity: O(n4)O(n^4)[code]class Solution(object): def multiply(self, A, B): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ if len(A)==0 or len(B)==0: return 0 m, n = len(A), len(B[0]) res = [ [0]*n for i in range(m) ] for i in range(m): i_zero = False for j in range(n): if i_zero==True: res[i][j] = 0 temp = 0 for i_value in A[i]: if i_value!=0: i_zero = True for j_index in range(len(B)): j_value = B[j_index][j] temp += i_value*j_value res[i][j] = temp return res # second method # 1. scan all elem, record all non_zero elements # 2. find the intersection # def mul(self, list1, list2): # return sum( [temp1*temp2 for temp1, temp2 in zip(list1,list2)] )
Error
Time exceeded.The second try
AcceptTime complexity: O(n3)O(n^3)
Time : 400+ (s)
[code]class Solution(object): def multiply(self, A, B): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ if len(A)==0 or len(B)==0: return 0 m, n = len(A), len(B[0]) res = [ [0]*n for i in range(m) ] for i in range(m): i_zero = True for ind in range(n): if A[i][ind]!=0: i_zero = False break for j in range(n): if i_zero==True: res[i][j] = 0 continue for mul_ind in range(len(A[0])): res[i][j] += A[i][mul_ind] * B[mul_ind][j] return res
The third try
Acceptdid some optimizations
[code]class Solution(object): def multiply(self, A, B): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ if len(A)==0 or len(B)==0: return 0 m, n = len(A), len(B[0]) res = [ [0]*n for i in range(m) ] zerom, zeron = [True]*m, [True]*n for i in range(m): for index in range(len(A[0])): if A[i][index]!=0: zerom[i] = False break for i in range(n): for index in range(len(B)): if B[index][i]!=0: zeron[i] = False break for i in range(m): if zerom[i]==True: continue for j in range(n): if zeron[j]==True: continue for mul_ind in range(len(A[0])): res[i][j] += A[i][mul_ind] * B[mul_ind][j] return res
相关文章推荐
- 非类型模版参数
- objective-c数组的四种遍历方法总结
- C实现与 uint64_t 相同功能的类
- C语言还有不定参数
- Title_微信开放平台分账功能实战(Java版)
- NLPIR.user Not valid license or your license expired! 解决办法
- MediaRecorder录音
- UNIX环境高级编程笔记1-sysconf、pathconf和fpathconf函数
- 前端最重要的--莫过于细节
- Python之socket(套接字)补充
- 建立共享存储实验记录
- shiro默认拦截器
- 【bzoj 3615】MSS 分块 线段树的合并和拆分
- JS获取页面宽度高度
- <LeetCode OJ> Happy Number【202】
- JAVA TCP/IP Socket 编程(一)
- iOS开发-21UINavigationController导航控制器初始化 导航控制器栈的push和pop跳转理解
- AFNetWorking
- 给UILabel设置不同的字体和颜色
- Object C中静态属性