Skip to content

Commit e6cbc3f

Browse files
update post
1 parent aa9b319 commit e6cbc3f

File tree

1 file changed

+67
-1
lines changed

1 file changed

+67
-1
lines changed

_posts/2024-05-08-leetcode-238.md

Lines changed: 67 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,20 @@
22
layout: post
33
title: (Leetcode) 238 - Product of Array Except Self
44
categories: [스터디-알고리즘]
5-
tags: [자바, java, 리트코드, Leetcode, 알고리즘, algorithm, array, 배열]
5+
tags:
6+
[
7+
자바,
8+
java,
9+
리트코드,
10+
Leetcode,
11+
알고리즘,
12+
algorithm,
13+
array,
14+
배열,
15+
prefixSum,
16+
prefixProd,
17+
suffixProd,
18+
]
619
date: 2024-05-08 19:30:00 +0900
720
toc: true
821
---
@@ -164,3 +177,56 @@ public int[] productExceptSelf(int[] nums) {
164177
### TC, SC
165178

166179
시간 복잡도는 O(n)이고 공간 복잡도는 O(n)이다.
180+
181+
## prefixProd, suffixProd 로 해결하기 (24.05.29 추가)
182+
183+
[누적합(prefixSum)](https://en.wikipedia.org/wiki/Prefix_sum) 이라는 알고리즘이 있다.
184+
185+
이를 응용해서 prefixProd와 suffixProd 이란 것을 만든다.
186+
187+
참고로 prefixProd는 앞에서부터 진행하는 누적곱, suffixProd는 뒤에서부터 진행하는 누적곱이다.
188+
189+
### 예시
190+
191+
예시로 제공된 input 값을 사용해보면 다음과 같을 것이다.
192+
193+
- 입력 : [1, 2, 3, 4]
194+
- prefixProd : [1, 2, 6, 24]
195+
- suffixProd : [24, 24, 12, 4]
196+
- 결과 : [24, 12, 8, 6]
197+
- 결과의 각 값은 나 자신을 제외한 나머지 갑들의 곱이다.
198+
- 결과의 각 값은 prefixProd[i - 1] \* suffixProd[i + 1] 이다. 단. 인덱스 범위를 벗어낫을 경우는 1을 곱한다.
199+
- [1 \* suffixProd[1], prefixProd[0] \* suffixProd[2], prefixProd[1] \* suffixProd[3], prefixProd[2] \* 1]
200+
201+
### 코드
202+
203+
```java
204+
public int[] productExceptSelf(int[] nums) {
205+
int[] result = new int[nums.length];
206+
207+
int[] prefixProd = new int[nums.length];
208+
int[] suffixProd = new int[nums.length];
209+
210+
prefixProd[0] = nums[0];
211+
for (int i = 1; i < nums.length; i++) {
212+
prefixProd[i] = prefixProd[i-1] * nums[i];
213+
}
214+
215+
suffixProd[nums.length - 1] = nums[nums.length - 1];
216+
for (int i = nums.length - 2; i > -1; i--) {
217+
suffixProd[i] = suffixProd[i + 1] * nums[i];
218+
}
219+
220+
result[0] = suffixProd[1];
221+
result[nums.length - 1] = prefixProd[nums.length - 2];
222+
for (int i = 1; i < nums.length - 1; i++) {
223+
result[i] = prefixProd[i - 1] * suffixProd[i + 1];
224+
}
225+
226+
return result;
227+
}
228+
```
229+
230+
### TC, SC
231+
232+
시간 복잡도는 O(n)이고 공간 복잡도는 O(n)이다.

0 commit comments

Comments
 (0)