Skip to content

Commit 47bff47

Browse files
committed
feat: implement productExceptSelf function to calculate the product of array elements except self
1 parent f90d1bd commit 47bff47

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution:
2+
def productExceptSelf(self, nums: list[int]) -> list[int]:
3+
"""
4+
nums의 각 μ›μ†Œμ— λŒ€ν•΄μ„œ, κ·Έ μ›μ†Œλ₯Ό μ œμ™Έν•œ λ‚˜λ¨Έμ§€ μ›μ†Œλ“€μ˜ 곱을 κ΅¬ν•˜λŠ” ν•¨μˆ˜
5+
μ‹œκ°„μ œμ•½μ€ O(n)이고, λ‚˜λˆ—μ…ˆμ„ μ‚¬μš©ν•˜μ§€ μ•Šμ•„μ•Ό 함
6+
7+
방법:
8+
1. brute-force. 각 μ›μ†Œλ§ˆλ‹€, λ‚˜λ¨Έμ§€ μ›μ†Œλ“€μ˜ 곱을 κ΅¬ν•˜κΈ°. O(n)의 μ‹œκ°„ μ œμ•½μ„ λ§Œμ‘±ν•˜μ§€ λͺ»ν•¨
9+
2. 전체 곱을 ꡬ해두고, 각 μ›μ†Œλ§ˆλ‹€ 자기 μžμ‹ μ˜ κ°’μœΌλ‘œ λ‚˜λˆ„κΈ°. λ‚˜λˆ—μ…ˆ μ œμ•½μ— κ±Έλ € μ‚¬μš© λΆˆκ°€
10+
3. λ£¨ν”„μ—μ„œ μžμ‹ μ˜ μ›μ†Œλ₯Ό λΉΌκ³  μ•žμ˜ κ°’λ“€μ˜ κ³±κ³Ό λ’€μ˜ κ³±λ“€μ˜ 값을 κ΅¬ν•˜κΈ°.
11+
- μ•žμ—μ„œλΆ€ν„° 곱을 κ΅¬ν•΄λ‚˜κ°€λ©΄μ„œ, 배열에 μ €μž₯ν•˜κΈ°. 초기 값은 1둜 μ„€μ •
12+
- λ’€μ—μ„œλΆ€ν„° 곱을 κ΅¬ν•΄λ‚˜κ°€λ©΄μ„œ, 배열에 μ €μž₯ν•˜κΈ°. 초기 값은 1둜 μ„€μ •
13+
- ν˜„ μœ„μΉ˜ κΈ°μ€€ μ•žμ˜ κ³±κ³Ό λ’€μ˜ 곱을 κ³±ν•΄μ„œ μ΅œμ’… 닡을 κ΅¬ν•˜κΈ°
14+
-> μ•žμ˜ κ³±κ³Ό λ’€μ˜ 곱의 λͺ©λ‘μ„ μœ μ§€ν•˜λ‹ˆ 곡간 λ³΅μž‘λ„κ°€ O(n), 더 νš¨μœ¨ν™” ν•  수 μ—†μ„κΉŒ?
15+
4. λ³„λ„μ˜ 배열을 λ§Œλ“€μ§€ μ•Šκ³ , μ•žμ—μ„œλΆ€ν„° κ³±ν•˜λ©° 배열에 μ €μž₯ν•œ ν›„, λ’€μ—μ„œλΆ€ν„° λ‹€μ‹œ κ³±ν•˜λ©° 동일 배열에 μ—…λ°μ΄νŠΈ.
16+
-> μ‹œκ°„λ³΅μž‘λ„ O(n), κ³΅κ°„λ³΅μž‘λ„ O(1) (λ‹΅ λ°°μ—΄ μ œμ™Έ)
17+
18+
Args:
19+
nums (list[int]): μ •μˆ˜ λͺ©λ‘
20+
21+
Returns:
22+
list[int]: 각 μ›μ†Œμ— λŒ€ν•΄μ„œ, κ·Έ μ›μ†Œλ₯Ό μ œμ™Έν•œ λ‚˜λ¨Έμ§€ μ›μ†Œλ“€μ˜ 곱을 담은 λͺ©λ‘
23+
"""
24+
answer = [1] * len(nums)
25+
nxt = 1
26+
for idx, num in enumerate(nums):
27+
answer[idx] = nxt
28+
nxt *= num
29+
nxt = 1
30+
for idx in range(len(nums)-1, -1, -1):
31+
answer[idx] *= nxt
32+
nxt *= nums[idx]
33+
return answer

0 commit comments

Comments
Β (0)