Skip to content

Commit e31138c

Browse files
committed
Update 238-Product-of-Array-Except-Self.java
Added solution set that doesn't accumulate extra memory, uses nums[] as prefix table.
1 parent f2e0cf0 commit e31138c

File tree

1 file changed

+30
-13
lines changed

1 file changed

+30
-13
lines changed

java/238-Product-of-Array-Except-Self.java

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,35 @@
33
//In first pass calculate the left product except self and in second calculate the right
44

55
class Solution {
6+
public int[] productExceptSelf(int[] nums) {
7+
int[] arr = new int[nums.length];
8+
int right = 1, left = 1;
9+
for (int i = 0; i < nums.length; i++) {
10+
arr[i] = left;
11+
left *= nums[i];
12+
}
13+
for (int i = nums.length - 1; i >= 0; i--) {
14+
arr[i] *= right;
15+
right *= nums[i];
16+
}
17+
return arr;
18+
}
619

7-
public int[] productExceptSelf(int[] nums) {
8-
int[] arr = new int[nums.length];
9-
int right=1, left=1;
10-
for (int i = 0; i < nums.length; i++) {
11-
arr[i] = left;
12-
left *= nums[i];
13-
}
14-
for(int i = nums.length - 1; i >= 0; i--) {
15-
arr[i] *= right;
16-
right *= nums[i];
17-
}
18-
return arr;
19-
}
20+
// using nums[] as the prefix calculation table
21+
public int[] productExceptSelfNumsAsPrefix(int[] nums) {
22+
int[] output = new int[nums.length];
23+
output[0] = 1; // default prefix is 1.
24+
25+
// prefix
26+
for (int i = 0; i < nums.length - 1; i++)
27+
output[i + 1] = output[i] * nums[i];
28+
29+
// postfix
30+
// we start at nums.length - 2 because multiplying by 1 is silly.
31+
for (int i = nums.length - 2; i >= 0; i--) {
32+
output[i] = nums[i + 1] * output[i];
33+
nums[i] = nums[i] * nums[i + 1];
34+
}
35+
return output;
36+
}
2037
}

0 commit comments

Comments
 (0)