Skip to content

Commit

Permalink
Solved "239. Product of Array Except Self"
Browse files Browse the repository at this point in the history
  • Loading branch information
KwonNayeon committed Dec 27, 2024
1 parent 58d4dd3 commit 15eca17
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions product-of-array-except-self/KwonNayeon.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""
Constraints:
1. 2 <= nums.length <= 10^5
2. -30 <= nums[i] <= 30
3. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer
Time Complexity: O(n)
- 배열을 두 번 μˆœνšŒν•˜λ―€λ‘œ O(n)
Space Complexity: O(1)
- 좜λ ₯ λ°°μ—΄(answer)을 μ œμ™Έν•˜λ©΄ μΆ”κ°€ 곡간이 μƒμˆ˜λ§ŒνΌλ§Œ ν•„μš”(left, right λ³€μˆ˜)
풀이 방법:
1. answer 배열을 1둜 μ΄ˆκΈ°ν™” (κ³±μ…ˆμ—μ„œλŠ” 1이 영ν–₯을 주지 μ•ŠμŒ)
2. μ™Όμͺ½μ—μ„œ 였λ₯Έμͺ½μœΌλ‘œ 순회:
- answer[i]에 ν˜„μž¬κΉŒμ§€μ˜ left λˆ„μ κ°’μ„ 곱함
- left *= nums[i]둜 λ‹€μŒμ„ μœ„ν•΄ left 값을 μ—…λ°μ΄νŠΈ
3. 였λ₯Έμͺ½μ—μ„œ μ™Όμͺ½μœΌλ‘œ 순회 (range(n-1, -1, -1) μ‚¬μš©):
- answer[i]에 ν˜„μž¬κΉŒμ§€μ˜ right λˆ„μ κ°’μ„ 곱함
- right *= nums[i]둜 λ‹€μŒμ„ μœ„ν•΄ right 값을 μ—…λ°μ΄νŠΈ
"""

class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
answer = [1] * n

left = 1
for i in range(n):
answer[i] *= left
left *= nums[i]

right = 1
for i in range(n-1, -1, -1):
answer[i] *= right
right *= nums[i]

return answer

0 comments on commit 15eca17

Please sign in to comment.