-
Notifications
You must be signed in to change notification settings - Fork 0
/
238. Product of Array Except Self
56 lines (44 loc) · 1.58 KB
/
238. Product of Array Except Self
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
49
50
51
52
53
54
55
56
/*
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].
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Constraint: It's guaranteed that the product of the elements of any prefix or suffix
of the array (including the whole array) fits in a 32 bit integer.
Note: Please solve it without division and in O(n).
*/
class Solution {
public int[] productExceptSelf(int[] nums) {
int[] leftProducts = new int[nums.length];
int[] rightProducts = new int[nums.length];
int[] result = new int[nums.length];
leftProducts[0] = 1;
for(int i = 1; i < nums.length; i++){
leftProducts[i] = leftProducts[i-1] * nums [i - 1];
}
// leftProducts = [1,1,2,6]
rightProducts[nums.length - 1] = 1;
for(int i = nums.length - 2; i >= 0; i--){
rightProducts[i] = rightProducts[i+1] * nums[i + 1];
}
// rightProducts = [24,12,4,1]
for(int i = 0; i < nums.length; i++){
result[i] = leftProducts[i] * rightProducts[i];
}
return result;
}
public int[] productExceptSelf(int[] nums) {
int[] result = new int[nums.length];
result[0] = 1;
for (int i = 1; i < nums.length; i++) {
result[i] = result[i - 1] * nums[i - 1];
}
int right = 1;
for (int i = nums.length - 1; i >= 0; i--) {
result[i] *= right;
right *= nums[i];
}
return result;
}
}