-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProductOfArrayExceptSelf.java
More file actions
28 lines (24 loc) · 956 Bytes
/
ProductOfArrayExceptSelf.java
File metadata and controls
28 lines (24 loc) · 956 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
/**
* 238. Product of Array Except Self
*
* Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
* The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
* You must write an algorithm that runs in O(n) time and without using the division operation.
*/
class ProductOfArrayExceptSelf {
public int[] productExceptSelf(int[] theNums) {
int n = theNums.length;
int[] prefix = new int[n];
int[] suffix = new int[n];
int[] answer = new int[n];
prefix[0] = 1;
for (int i = 1; i < n; i++)
prefix[i] = prefix[i - 1] * theNums[i - 1];
suffix[n - 1] = 1;
for (int i = n - 2; i >= 0; i--)
suffix[i] = suffix[i + 1] * theNums[i + 1];
for (int i = 0; i < n; i++)
answer[i] = prefix[i] * suffix[i];
return answer;
}
}