Skip to content

Commit 8627a2c

Browse files
committed
238. Product of Array Except Self
1 parent 13db2b8 commit 8627a2c

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
public int[] productExceptSelf(int[] nums) {
3+
// time complexity: O(n)
4+
// space complexity: O(n)
5+
int[] left = new int[nums.length];
6+
int[] right = new int[nums.length];
7+
8+
// nums = [1, 2, 3, 4]
9+
10+
// left = [1, 1, 2, 6]
11+
// right = [24, 12, 4, 1]
12+
13+
// nums => [24, 12, 8, 6]
14+
left[0] = 1;
15+
for (int i = 1; i < nums.length; i++) {
16+
left[i] = left[i-1] * nums[i-1];
17+
}
18+
19+
right[right.length-1] = 1;
20+
for (int i = nums.length - 2; i >= 0; i--) {
21+
right[i] = right[i+1] * nums[i+1];
22+
}
23+
24+
for (int i = 0; i < nums.length; i++) {
25+
nums[i] = left[i] * right[i];
26+
}
27+
return nums;
28+
}
29+
}

0 commit comments

Comments
 (0)