|
| 1 | +""" |
| 2 | +[Problem] |
| 3 | +https://leetcode.com/problems/product-of-array-except-self/ |
| 4 | +
|
| 5 | +λ°°μ΄ numsκ° μ£Όμ΄μ‘μ λ, λ°°μ΄ answerλ₯Ό λ°νν΄λΌ. |
| 6 | +answer[i]λ nums[i]λ₯Ό μ μΈν λͺ¨λ μμλ€μ κ³±μ΄μ΄μΌ νλ€. |
| 7 | +
|
| 8 | +[Brainstorming] |
| 9 | +μ 체 μμλ€μ κ³±μ ꡬνλ€. ν΄λΉ μμλ§ λλμ
μΌλ‘ μ μΈνλ€. |
| 10 | +-> μ΄ λ°©μμ λ€λ£¨κΈ° μ΄λ ΅λ€. 0μ΄ λ€μ΄κ° μ μμ. |
| 11 | +
|
| 12 | +Brute Force λ°©μμΌλ‘ λ°μ λ μ€λ₯΄μ§ μμ.. |
| 13 | +O(n)μΌλ‘ μ΄λ»κ² ν μ μμ§? |
| 14 | +
|
| 15 | +""" |
| 16 | +from typing import List |
| 17 | +class Solution: |
| 18 | + """ |
| 19 | + another solution |
| 20 | + ref: https://www.algodale.com/problems/product-of-array-except-self/ |
| 21 | +
|
| 22 | + [Brainstorming] |
| 23 | + κ° μΈλ±μ€ μμλ₯Ό μ μΈν μμλ€μ κ³±μ μλμ κ°λ€. |
| 24 | + nums[0] * nums[1] * ... * nums[index - 1] * nums[index + 1] * ... nums[len(nums) - 1] |
| 25 | + μ¦, nums[index] μ μ κ³±μ λμ ν λ°°μ΄κ³Ό, nums[index] μ΄νμ κ³±μ λμ ν λ°°μ΄μ ꡬνλ©΄ λ΅μ ꡬν μ μλ€. |
| 26 | +
|
| 27 | + [Complexity] |
| 28 | + N: nums.length |
| 29 | + Time: O(N) |
| 30 | + Space: O(N) |
| 31 | + """ |
| 32 | + def productExceptSelf(self, nums: List[int]) -> List[int]: |
| 33 | + before_products = [1] * len(nums) |
| 34 | + for index in range(1, len(nums)): |
| 35 | + before_products[index] = before_products[index - 1] * nums[index- 1] |
| 36 | + |
| 37 | + after_products = [1] * len(nums) |
| 38 | + for index in range(len(nums) - 2, -1, -1): |
| 39 | + after_products[index] = after_products[index + 1] * nums[index + 1] |
| 40 | + |
| 41 | + answer = [] |
| 42 | + for index in range(len(nums)): |
| 43 | + answer.append(before_products[index] * after_products[index]) |
| 44 | + |
| 45 | + return answer |
| 46 | + |
| 47 | +sol = Solution() |
| 48 | +print(sol.productExceptSelf([1,2,3,4])) |
| 49 | +print(sol.productExceptSelf([-1,1,0,-3,3])) |
| 50 | +print(sol.productExceptSelf([2,3,4,5])) |
| 51 | + |
| 52 | + |
0 commit comments