File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ # Approach
3+ λͺ¨λ μμλΌλ¦¬ κ³±ν λ€μμ nums λ°°μ΄μ μννλ©° κ·Έ κ°μ ν΄λΉ μμλ‘ λλλ€.
4+ μ΄λ 0μ κ°μμ 0μ μ μΈν κ³±μ κ°λ κ°μ΄ ꡬνλ€.
5+ 0μ΄ 2κ° μ΄μμ΄λ©΄ μ λ΅μ λͺ¨λ 0μ΄λ©°,
6+ 0μ΄ 1κ°λ©΄ 0μ μ μΈν κ³±μ κ°μ μ¬μ©νλ€.
7+
8+ # Complexity
9+ - Time complexity: O(n)
10+
11+ - Space complexity: O(n)
12+ """
13+
14+
15+ # Code
16+ class Solution :
17+ def productExceptSelf (self , nums : List [int ]) -> List [int ]:
18+ product = 1
19+ non_zero_product = 1
20+ zero_count = 0
21+ for num in nums : # O(n) Time complexity
22+ if num == 0 :
23+ zero_count += 1
24+ non_zero_product *= 1
25+ else :
26+ non_zero_product *= num
27+ product *= num
28+
29+ if zero_count > 1 :
30+ return [0 ] * len (nums ) # O(n) space complexity
31+
32+ answer = [] # O(n) space complexity
33+ for i in range (len (nums )): # O(n) Time complexity
34+ if nums [i ] == 0 :
35+ answer .append (non_zero_product )
36+ else :
37+ answer .append (int (product / nums [i ]))
38+ return answer
You canβt perform that action at this time.
0 commit comments