File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def productExceptSelf (self , nums : List [int ]) -> List [int ]:
3
+ # Solution 1 :모든 수를 미리 곱해두기
4
+ # 0을 포함한다면 미리 0의 개수를 체크해두기
5
+
6
+ n = len (nums )
7
+ ret = [0 for _ in range (n )]
8
+ """
9
+ all_product = 1
10
+ non_zero_product = 1
11
+ zero_cnt = 0
12
+
13
+ for x in nums:
14
+ all_product *= x
15
+
16
+ if x == 0:
17
+ zero_cnt += 1
18
+ else:
19
+ non_zero_product *= x
20
+
21
+ if zero_cnt > 1:
22
+ return ret
23
+
24
+ for i in range(n):
25
+ if nums[i] == 0:
26
+ ans = non_zero_product
27
+ else:
28
+ ans = all_product // nums[i]
29
+ ret[i] = ans
30
+ return ret
31
+ """
32
+
33
+ # Solution 2 : w/o division
34
+ # prefix sum과 같이 풀이 진행
35
+ # Tc : O(n) / Sc : O(n) - no extra memory
36
+
37
+ prefix_pr , postfix_pr = 1 , 1
38
+ for i in range (n ):
39
+ ret [i ] = prefix_pr
40
+ prefix_pr *= nums [i ]
41
+ for i in range (n - 1 , - 1 , - 1 ):
42
+ ret [i ] *= postfix_pr
43
+ postfix_pr *= nums [i ]
44
+ return ret
45
+
46
+
You can’t perform that action at this time.
0 commit comments