Skip to content

Commit 15eca17

Browse files
committed
Solved "239. Product of Array Except Self"
1 parent 58d4dd3 commit 15eca17

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
"""
2+
Constraints:
3+
1. 2 <= nums.length <= 10^5
4+
2. -30 <= nums[i] <= 30
5+
3. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer
6+
7+
Time Complexity: O(n)
8+
- 배열을 두 번 μˆœνšŒν•˜λ―€λ‘œ O(n)
9+
10+
Space Complexity: O(1)
11+
- 좜λ ₯ λ°°μ—΄(answer)을 μ œμ™Έν•˜λ©΄ μΆ”κ°€ 곡간이 μƒμˆ˜λ§ŒνΌλ§Œ ν•„μš”(left, right λ³€μˆ˜)
12+
13+
풀이 방법:
14+
1. answer 배열을 1둜 μ΄ˆκΈ°ν™” (κ³±μ…ˆμ—μ„œλŠ” 1이 영ν–₯을 μ£Όμ§€ μ•ŠμŒ)
15+
2. μ™Όμͺ½μ—μ„œ 였λ₯Έμͺ½μœΌλ‘œ 순회:
16+
- answer[i]에 ν˜„μž¬κΉŒμ§€μ˜ left λˆ„μ κ°’μ„ 곱함
17+
- left *= nums[i]둜 λ‹€μŒμ„ μœ„ν•΄ left 값을 μ—…λ°μ΄νŠΈ
18+
3. 였λ₯Έμͺ½μ—μ„œ μ™Όμͺ½μœΌλ‘œ 순회 (range(n-1, -1, -1) μ‚¬μš©):
19+
- answer[i]에 ν˜„μž¬κΉŒμ§€μ˜ right λˆ„μ κ°’μ„ 곱함
20+
- right *= nums[i]둜 λ‹€μŒμ„ μœ„ν•΄ right 값을 μ—…λ°μ΄νŠΈ
21+
"""
22+
23+
class Solution:
24+
def productExceptSelf(self, nums: List[int]) -> List[int]:
25+
n = len(nums)
26+
answer = [1] * n
27+
28+
left = 1
29+
for i in range(n):
30+
answer[i] *= left
31+
left *= nums[i]
32+
33+
right = 1
34+
for i in range(n-1, -1, -1):
35+
answer[i] *= right
36+
right *= nums[i]
37+
38+
return answer

0 commit comments

Comments
Β (0)