Question
Given sparse matrices A and B, return the result of AB.
You could 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 |
Hide company Tags LinkedIn
Hide Tags Hash Table My First try
Time Complexity:o (N4) O (n^4)
Class solution (Object): Def multiply (self, A, B): "" ": Type A:list[list[int]]: type b:list[l Ist[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 to Temp1, Temp2 in ZIP (LIST1,LIST2)])
Error
Time exceeded. The second try
Accept
Time Complexity:o (n3) O (n^3)
time:400+ (s)
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
Accept
Did some optimizations
Class solution (Object): Def multiply (self, A, B): "" ": Type A:list[list[int]]: type b:list[l Ist[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:co
Ntinue for Mul_ind in range (len (a[0)): res[i][j] + = a[i][mul_ind] * B[mul_ind][j] return res