Skip to content

Commit 3d25456

Browse files
committed
feat: [Week 03-3] solve product-of-array-except-self
1 parent dc8c121 commit 3d25456

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
"""
2+
solution 1:
3+
์™ผ์ชฝ๋ถ€ํ„ฐ ๊ณฑํ•ด๊ฐ€๋Š” prefix,
4+
์˜ค๋ฅธ์ชฝ๋ถ€ํ„ฐ ๊ณฑํ•ด๊ฐ€๋Š” postfix,
5+
2๊ฐ€์ง€์˜ ๋ฐฐ์—ด์„ ๋งŒ๋“ ๋‹ค.
6+
7+
nums = [1,2,3,4]
8+
prefix = [1,2,6,24]
9+
postfix = [24,12,4,1]
10+
11+
์ดํ›„ ์ •๋‹ต ๋ฐฐ์—ด result[i] = prefix[i - 1] * postfix[i + 1] ์ด ๋˜๋„๋ก ๋งŒ๋“ ๋‹ค.
12+
0, n-1 ๋ฒˆ์งธ ์ธ๋ฑ์Šค์—์„  ์˜ˆ์™ธ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ค€๋‹ค.
13+
14+
Time: O(n) = prefix ๊ณ„์‚ฐ O(n) + postfix ๊ณ„์‚ฐ O(n) + result ๊ณ„์‚ฐ O(n)
15+
Space: O(n) = prefix ๋ฐฐ์—ด O(n) + postfix ๋ฐฐ์—ด O(n)
16+
"""
17+
18+
# class Solution:
19+
# def productExceptSelf(self, nums: List[int]) -> List[int]:
20+
# n = len(nums)
21+
22+
# prefix = [1 for i in range(n)]
23+
# postfix = [1 for i in range(n)]
24+
25+
# prefix[0] = nums[0]
26+
# for i in range(1, n):
27+
# prefix[i] = prefix[i-1] * nums[i]
28+
29+
# postfix[n - 1] = nums[n - 1]
30+
# for i in range(n-2, -1, -1):
31+
# postfix[i] = postfix[i + 1] * nums[i]
32+
33+
# result = []
34+
# for i in range(n):
35+
# pre = prefix[i - 1] if i - 1 >= 0 else 1
36+
# post = postfix[i + 1] if i + 1 < n else 1
37+
# result.append(pre * post)
38+
# return result
39+
40+
"""
41+
์ตœ์ ํ™” ํ’€์ด
42+
Solution:
43+
prefix, postfix ๋ฐฐ์—ด ์ €์žฅ ์—†์ด ์ˆœํšŒํ•˜๋ฉฐ ๋ฐ”๋กœ prefix, postfix ๋ฅผ ๊ณฑํ•ด์„œ result ๋ฐฐ์—ด์— ๋‹ด๋Š”๋‹ค.
44+
45+
Time: O(n) = O(2n)
46+
Space: O(1)
47+
"""
48+
49+
50+
class Solution:
51+
def productExceptSelf(self, nums: List[int]) -> List[int]:
52+
n = len(nums)
53+
result = [1] * n
54+
55+
prefix = 1
56+
for i in range(n):
57+
result[i] *= prefix
58+
prefix *= nums[i]
59+
60+
postfix = 1
61+
for i in range(n - 1, -1, -1):
62+
result[i] *= postfix
63+
postfix *= nums[i]
64+
65+
return result

0 commit comments

Comments
ย (0)