Skip to content

Commit 3a3e87b

Browse files
committed
Solve: product of array except self
1 parent 421f1de commit 3a3e87b

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution:
2+
# 정수 배열에 대해 answer 배열을 반환
3+
# 1. 정답 배열의 i번째 요소는 정수 배열의 i번째 요소를 제외한 다른 모든 요소의 곱
4+
# 2. 시간복잡도는 O(n) 이내로 해결 필요
5+
def productExceptSelf(self, nums: List[int]) -> List[int]:
6+
length = len(nums)
7+
answer = [1] * length # 1로 초기화
8+
9+
# 왼쪽 곱 계산 후 answer에 저장
10+
left = 1
11+
for i in range(length):
12+
answer[i] = left
13+
left *= nums[i]
14+
15+
# 오른쪽 곱을 누적하면서 answer에 곱하기
16+
right = 1
17+
for i in range(length - 1, -1, -1):
18+
answer[i] *= right
19+
right *= nums[i]
20+
21+
return answer
22+

0 commit comments

Comments
 (0)