Skip to content

Commit a7ee851

Browse files
committed
add product-of-array-except-self solution
1 parent 3379850 commit a7ee851

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
"""
2+
[Problem]
3+
https://leetcode.com/problems/product-of-array-except-self/
4+
5+
λ°°μ—΄ numsκ°€ μ£Όμ–΄μ‘Œμ„ λ•Œ, λ°°μ—΄ answerλ₯Ό λ°˜ν™˜ν•΄λΌ.
6+
answer[i]λŠ” nums[i]λ₯Ό μ œμ™Έν•œ λͺ¨λ“  μš”μ†Œλ“€μ˜ 곱이어야 ν•œλ‹€.
7+
8+
[Brainstorming]
9+
전체 μš”μ†Œλ“€μ˜ 곱을 κ΅¬ν•œλ‹€. ν•΄λ‹Ή μš”μ†Œλ§Œ λ‚˜λˆ—μ…ˆμœΌλ‘œ μ œμ™Έν•œλ‹€.
10+
-> 이 방식은 닀루기 μ–΄λ ΅λ‹€. 0이 λ“€μ–΄κ°ˆ 수 있음.
11+
12+
Brute Force λ°©μ‹μœΌλ‘œ 밖에 λ– μ˜€λ₯΄μ§€ μ•ŠμŒ..
13+
O(n)으둜 μ–΄λ–»κ²Œ ν’€ 수 μžˆμ§€?
14+
15+
"""
16+
from typing import List
17+
class Solution:
18+
"""
19+
another solution
20+
ref: https://www.algodale.com/problems/product-of-array-except-self/
21+
22+
[Brainstorming]
23+
각 인덱슀 μš”μ†Œλ₯Ό μ œμ™Έν•œ μš”μ†Œλ“€μ˜ 곱은 μ•„λž˜μ™€ κ°™λ‹€.
24+
nums[0] * nums[1] * ... * nums[index - 1] * nums[index + 1] * ... nums[len(nums) - 1]
25+
즉, nums[index] μ „μ˜ 곱을 λˆ„μ ν•œ λ°°μ—΄κ³Ό, nums[index] μ΄ν›„μ˜ 곱을 λˆ„μ ν•œ 배열을 κ΅¬ν•˜λ©΄ 닡을 ꡬ할 수 μžˆλ‹€.
26+
27+
[Complexity]
28+
N: nums.length
29+
Time: O(N)
30+
Space: O(N)
31+
"""
32+
def productExceptSelf(self, nums: List[int]) -> List[int]:
33+
before_products = [1] * len(nums)
34+
for index in range(1, len(nums)):
35+
before_products[index] = before_products[index - 1] * nums[index- 1]
36+
37+
after_products = [1] * len(nums)
38+
for index in range(len(nums) - 2, -1, -1):
39+
after_products[index] = after_products[index + 1] * nums[index + 1]
40+
41+
answer = []
42+
for index in range(len(nums)):
43+
answer.append(before_products[index] * after_products[index])
44+
45+
return answer
46+
47+
sol = Solution()
48+
print(sol.productExceptSelf([1,2,3,4]))
49+
print(sol.productExceptSelf([-1,1,0,-3,3]))
50+
print(sol.productExceptSelf([2,3,4,5]))
51+
52+

0 commit comments

Comments
Β (0)