1. 숫자 기준 왼쪽, 오른쪽 곱배열을 구한 뒤 곱배열을 곱해서 반환
from typing import *
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
answer = []
temp1 = [1]
for i in range(1, len(nums)):
temp1.append(temp1[-1] * nums[i - 1])
temp2 = [1]
for i in range(len(nums) - 1, 0, -1):
temp2.append(temp2[-1] * nums[i])
for i in range(len(temp1)):
answer.append(temp1[i] * temp2[::-1][i])
return answer
2. 동일한 원리, 최적화
from typing import *
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
answer = [1]
for i in range(1, len(nums)):
answer.append(answer[-1] * nums[i - 1])
temp = 1
for i in range(len(nums) - 1, -1, -1):
answer[i] = answer[i] * temp
temp *= nums[i]
return answer
'Algorithm' 카테고리의 다른 글
310. Minimum Height Trees (0) | 2021.04.08 |
---|---|
287. Find the Duplicate Number (0) | 2021.04.07 |
46. Permutations (0) | 2021.04.05 |
94. Binary Tree Inorder Traversal (0) | 2021.04.05 |
22. Generate Parentheses (0) | 2021.04.05 |