Skip to content

Commit 9a907f1

Browse files
product Except self solution
1 parent 4662d97 commit 9a907f1

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class SolutionProductExceptSelf {
2+
3+
public int[] productExceptSelf(int[] nums) {
4+
// answer[i] = nums[0] * nums[1] * ... * nums[i-1] * nums[i+1] * ... * nums[n-1]
5+
// answer[i] = left[i] * right[i]
6+
// left[i] = nums[0] * nums[1] * ... * nums[i-1]
7+
// right[i] = nums[i+1] * ... * nums[n-1]
8+
// left[i] = left[i-1] * nums[i-1]
9+
// right[i] = right[i+1] * nums[i+1]
10+
// answer[i] = left[i] * right[i]
11+
// 시간복잡도: O(N), 공간복잡도: O(N)
12+
int n = nums.length;
13+
int[] left = new int[n];
14+
int[] right = new int[n];
15+
int[] answer = new int[n];
16+
17+
left[0] = 1;
18+
right[n - 1] = 1;
19+
20+
for (int i = 1; i < n; i++) {
21+
left[i] = left[i - 1] * nums[i - 1];
22+
}
23+
24+
for (int i = n - 2; i >= 0; i--) {
25+
right[i] = right[i + 1] * nums[i + 1];
26+
}
27+
28+
for (int i = 0; i < n; i++) {
29+
answer[i] = left[i] * right[i];
30+
}
31+
32+
return answer;
33+
}
34+
}

0 commit comments

Comments
 (0)