File tree Expand file tree Collapse file tree 1 file changed +21
-12
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +21
-12
lines changed Original file line number Diff line number Diff line change 11class Solution :
22 def productExceptSelf (self , nums : List [int ]) -> List [int ]:
3- total_product = 1
3+ answer = []
44
5- for num in nums :
6- if num != 0 :
7- total_product *= num
8-
9- if nums .count (0 ) == 1 :
10- return [0 if num != 0 else total_product for num in nums ]
11- elif nums .count (0 ) > 1 :
12- return [0 for _ in range (len (nums ))]
13- else :
14- return [total_product // num for num in nums ]
15-
5+ product1 = [0 ] * len (nums )
6+ product2 = [0 ] * len (nums )
7+
8+ product1 [0 ] = nums [0 ]
9+
10+ for i in range (1 , len (nums )):
11+ product1 [i ] = product1 [i - 1 ]* nums [i ]
1612
13+ product2 [- 1 ] = nums [- 1 ]
1714
15+ for i in range (len (nums )- 2 , - 1 , - 1 ):
16+ product2 [i ] = product2 [i + 1 ] * nums [i ]
17+
18+ for i in range (len (nums )):
19+ if i == 0 :
20+ answer .append (product2 [1 ])
21+ elif i == len (nums )- 1 :
22+ answer .append (product1 [- 2 ])
23+ else :
24+ answer .append (product1 [i - 1 ]* product2 [i + 1 ])
25+ return answer
26+
You can’t perform that action at this time.
0 commit comments