|
4 | 4 |
|
5 | 5 | public class ProductOfArrayExceptItself {
|
6 | 6 |
|
7 |
| - private record ProductDetails(int nonZeroProduct, int numberOfZeros) { } |
8 |
| - |
9 | 7 | public int[] productExceptSelf(int[] nums) {
|
10 |
| - final ProductDetails productDetails = getProductDetails(nums); |
11 |
| - if (productDetails.numberOfZeros > 1) return new int[nums.length]; |
12 |
| - if (productDetails.numberOfZeros == 1) return productSumOnlyWhenZero(nums, productDetails.nonZeroProduct); |
13 | 8 | final int[] result = new int[nums.length];
|
14 |
| - for (int i = 0 ; i < result.length ; i++) { |
15 |
| - result[i] = productDetails.nonZeroProduct / nums[i]; |
16 |
| - } |
| 9 | + multipleWithLeftPrefix(nums, result); |
| 10 | + multiplyWithRightPostfix(nums, result); |
17 | 11 | return result;
|
18 | 12 | }
|
19 | 13 |
|
20 |
| - private int[] productSumOnlyWhenZero(int[] array, int product) { |
21 |
| - final int[] result = new int[array.length]; |
22 |
| - for (int i = 0 ; i < array.length ; i++) { |
23 |
| - if (array[i] == 0) result[i] = product; |
| 14 | + private void multipleWithLeftPrefix(int[] numbers, int[] result) { |
| 15 | + result[0] = 1; |
| 16 | + for(int i = 1 ; i < numbers.length ; i++) { |
| 17 | + result[i] = result[i - 1] * numbers[i - 1]; |
24 | 18 | }
|
25 |
| - return result; |
26 | 19 | }
|
27 | 20 |
|
28 |
| - private ProductDetails getProductDetails(int[] array) { |
29 |
| - int numberOfZeros = 0; |
30 |
| - int nonZeroProduct = 1; |
31 |
| - for (int element : array) { |
32 |
| - if (element == 0) numberOfZeros++; |
33 |
| - else nonZeroProduct *= element; |
| 21 | + private void multiplyWithRightPostfix(int[] numbers, int[] result) { |
| 22 | + int right = 1; |
| 23 | + for(int i = result.length - 1 ; i >= 0 ; i--) { |
| 24 | + result[i] *= right; |
| 25 | + right *= numbers[i]; |
34 | 26 | }
|
35 |
| - return new ProductDetails(nonZeroProduct, numberOfZeros); |
36 | 27 | }
|
37 | 28 | }
|
0 commit comments