Skip to content

Commit 588fe0e

Browse files
committed
feat: Solve product-of-array-except-self problem
1 parent be7853c commit 588fe0e

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import math
2+
3+
class Solution:
4+
"""
5+
1. ์ธ๋ฑ์Šค ์Šฌ๋ผ์ด์‹ฑ์„ ํ™œ์šฉํ•œ ํ’€์ด
6+
- ์ธ๋ฑ์Šค ์Šฌ๋ผ์ด์‹ฑ์„ ํ™œ์šฉํ•˜์—ฌ ํ•ด๋‹น ์ธ๋ฑ์Šค๋ฅผ ์ œ์™ธํ•œ ๋‚˜๋จธ์ง€ ์›์†Œ๋“ค์˜ ๊ณฒ์„ math.prod()๋ฅผ ์ด์šฉํ•˜์—ฌ ๋ฐฐ์—ด์— ์‚ฝ์ž…
7+
- ์‹œ๊ฐ„์ดˆ๊ณผ O(n^2)
8+
2. DP Bottom Up ๋ฐฉ์‹์œผ๋กœ ํ’€์ด
9+
- ์ธ๋ฑ์Šค i์— ๋Œ€ํ•œ ์™ผ์ชฝ ๋ถ€๋ถ„๊ณผ ์˜ค๋ฅธ์ชฝ ๋ถ€๋ถ„์˜ ๊ณฑ์„ ๊ณ„์‚ฐํ•˜๋Š” ๋ฐฉ์‹
10+
- ์‹œ๊ฐ„ ๋ณต์žก๋„ O(n)
11+
- ๊ณต๊ฐ„ ๋ณต์žก๋„ O(1)
12+
"""
13+
# 1๋ฒˆ ํ’€์ด
14+
# def productExceptSelf(self, nums: List[int]) -> List[int]:
15+
# answer = [1] * len(n)
16+
17+
# for i in range(len(nums)):
18+
# answer.append(math.prod(nums[:i] + nums[i+1:]))
19+
20+
# return answer
21+
22+
def productExceptSelf(self, nums: List[int]) -> List[int]:
23+
dp = [1] * len(nums)
24+
25+
left = 1
26+
for i in range(len(nums)):
27+
dp[i] = left
28+
left *= nums[i]
29+
30+
right = 1
31+
for i in range(len(nums) - 1, -1, -1):
32+
dp[i] *= right
33+
right *= nums[i]
34+
return dp

0 commit comments

Comments
ย (0)