-
Notifications
You must be signed in to change notification settings - Fork 0
/
238.Product_of_Array_Except_Self.java
40 lines (40 loc) · 1.16 KB
/
238.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
35
36
37
38
39
40
class Solution {
public int[] productExceptSelf(int[] nums) {
int zeros = 0;
int lastZeroIndex = -1;
int[] out = new int[nums.length];
for (int i=0; i<nums.length; i++) {
if (nums[i] == 0) {
zeros++;
lastZeroIndex = i;
}
}
if (zeros > 1) {
return out;
} else if (zeros == 1) {
int prod = 1;
for (int n : nums) {
if (n != 0) {
prod *= n;
}
}
out[lastZeroIndex] = prod;
return out;
} else {
int[] pref = new int[nums.length];
int[] suff = new int[nums.length];
int pre = 1;
int suf = 1;
for (int i=0; i<nums.length; i++) {
pre *= nums[i];
pref[i] = pre;
suf *= nums[nums.length-1-i];
suff[nums.length-1-i] = suf;
}
for (int i=0; i<nums.length; i++) {
out[i] = (i>0 ? pref[i-1] : 1) * (i<nums.length-1 ? suff[i+1] : 1);
}
return out;
}
}
}