Skip to content

Commit a3dbcb2

Browse files
feat: product except self
1 parent fb485d9 commit a3dbcb2

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// time complexity: O(n)
2+
// space complexity: O(1)
3+
// prefix와 postfix를 이용하여 계산
4+
// 예를 들어, [1, 2, 3, 4] 일 때,
5+
// prefix는 [1, 1, 2, 6] 이고 postfix는 [24, 12, 4, 1] 이다.
6+
// 그리고 서로 곱하면 [24, 12, 8, 6] 이 된다.
7+
func productExceptSelf(nums []int) []int {
8+
res := make([]int, len(nums))
9+
for i := range res {
10+
res[i] = 1
11+
}
12+
13+
prefix := 1
14+
for i := 0; i < len(nums); i++ {
15+
res[i] = prefix
16+
prefix *= nums[i]
17+
}
18+
19+
postfix := 1
20+
for i := len(nums) - 1; i >= 0; i-- {
21+
res[i] *= postfix
22+
postfix *= nums[i]
23+
}
24+
25+
return res
26+
}

0 commit comments

Comments
 (0)