Skip to content

Commit 2b040fc

Browse files
committed
Add Solution.java for 0238.Product of Array Except Self
1 parent 5f57c7b commit 2b040fc

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Product of Array Except Self
2+
3+
Given an array **nums** of n integers where _n > 1_,  return an array **output** such that **output[i]** is equal to the product of all the elements of **nums** except **nums[i]**.
4+
5+
6+
## Example 1:
7+
```
8+
Input: [1,2,3,4]
9+
Output: [24,12,8,6]
10+
```
11+
12+
**Note**: Please solve it without division and in O(n).
13+
14+
15+
16+
**Follow up**:
17+
18+
Could you solve it with constant space complexity? (The output array **does not** count as extra space for the purpose of space complexity analysis.)
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution {
2+
public int[] productExceptSelf(int[] nums) {
3+
int len = nums.length;
4+
int[] output = new int[len];
5+
for (int i = 0, left = 1; i < len; i++) {
6+
output[i] = left;
7+
left *= nums[i];
8+
}
9+
for (int j = len - 1, right = 1; j >= 0; j--) {
10+
output[j] *= right;
11+
right *= nums[j];
12+
}
13+
return output;
14+
}
15+
}

0 commit comments

Comments
 (0)