-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path04.productexceptitself
More file actions
41 lines (32 loc) · 950 Bytes
/
04.productexceptitself
File metadata and controls
41 lines (32 loc) · 950 Bytes
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
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] result = new int[n];
// Step 1: Calculate prefix product
int prefix = 1;
for (int i = 0; i < n; i++) {
result[i] = prefix;
prefix *= nums[i];
}
// Step 2: Multiply with suffix product
int suffix = 1;
for (int i = n - 1; i >= 0; i--) {
result[i] *= suffix;
suffix *= nums[i];
}
return result;
// TLE
// int[] nums1=new int[n];
// for(int i=0;i<n;i++){
// int mul=1;
// for(int j=0;j<n;j++){
// if(i==j)
// continue;
// else
// mul*=nums[j];
// }
// nums1[i]=mul;
// }
// return nums1;
}
}