-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProductOfArrayExceptSelf.java
48 lines (39 loc) · 1.01 KB
/
ProductOfArrayExceptSelf.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
41
42
43
44
45
46
47
48
public class ProductOfArrayExceptSelf {
// Time Complexity: O(n)
// Space Complexity: O(1)
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] res = new int[n];
res[0] = 1;
for (int i = 1; i < n; i++) {
res[i] = res[i - 1] * nums[i - 1];
}
int postfix = 1;
for (int i = n - 1; i >= 0; i--) {
res[i] *= postfix;
postfix *= nums[i];
}
return res;
}
/*
Brute Force Approach
// Time Complexity: O(n^2)
// Space Complexity: O(1)
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] res = new int[n];
for (int i = 0; i < n; i++) {
int prod = 1;
for (int j = 0; j < n; j++) {
if (i != j) {
prod *= nums[j];
}
}
res[i] = prod;
}
return res;
}
*/
public static void main(String[] args) {
}
}