forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0238-product-of-array-except-self.java
34 lines (29 loc) · 1.04 KB
/
0238-product-of-array-except-self.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//Just store the left and right product (Try doing this with extra space first)
//This one is constant space because we are returning the array we created
//In first pass calculate the left product except self and in second calculate the right
classSolution {
publicint[] productExceptSelf(int[] nums) {
int[] arr = newint[nums.length];
intright = 1, left = 1;
for (inti = 0; i < nums.length; i++) {
arr[i] = left;
left *= nums[i];
}
for (inti = nums.length - 1; i >= 0; i--) {
arr[i] *= right;
right *= nums[i];
}
returnarr;
}
publicint[] productExceptSelfNumsAsPrefix(int[] nums) {
int[] output = newint[nums.length];
output[0] = 1;
for (inti = 0; i < nums.length - 1; i++) output[i + 1] =
output[i] * nums[i];
for (inti = nums.length - 2; i >= 0; i--) {
output[i] = nums[i + 1] * output[i];
nums[i] = nums[i] * nums[i + 1];
}
returnoutput;
}
}