-
Notifications
You must be signed in to change notification settings - Fork 56
/
Solution.java
28 lines (26 loc) · 886 Bytes
/
Solution.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
package g0201_0300.s0238_product_of_array_except_self;
// #Medium #Top_100_Liked_Questions #Array #Prefix_Sum #Data_Structure_II_Day_5_Array #Udemy_Arrays
// #Big_O_Time_O(n^2)_Space_O(n) #2022_07_04_Time_1_ms_(100.00%)_Space_50.8_MB_(85.60%)
public class Solution {
public int[] productExceptSelf(int[] nums) {
int product = 1;
int[] ans = new int[nums.length];
for (int num : nums) {
product = product * num;
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
ans[i] = product / nums[i];
} else {
int p = 1;
for (int j = 0; j < nums.length; j++) {
if (j != i) {
p = p * nums[j];
}
}
ans[i] = p;
}
}
return ans;
}
}