|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | /**
|
4 |
| - * Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. |
5 |
| -
|
6 |
| - Solve it without division and in O(n). |
7 |
| -
|
8 |
| - For example, given [1,2,3,4], return [24,12,8,6]. |
| 4 | + * 238. Product of Array Except Self |
| 5 | + * |
| 6 | + * Given an array of n integers where n > 1, nums, |
| 7 | + * return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. |
| 8 | + * Solve it without division and in O(n). |
| 9 | + * For example, given [1,2,3,4], return [24,12,8,6]. |
9 | 10 |
|
10 | 11 | Follow up:
|
11 |
| - Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.) |
| 12 | + Could you solve it with constant space complexity? |
| 13 | + (Note: The output array does not count as extra space for the purpose of space complexity analysis.) |
12 | 14 | */
|
| 15 | + |
13 | 16 | public class _238 {
|
14 | 17 |
|
| 18 | + /**Very straightforward idea: iterate through the array twice: |
| 19 | + * first time: get res[i] = res[i-1]*nums[i-1] |
| 20 | + * second time: have a variable called right, which means all the numbers product to its right, then do |
| 21 | + * res[i] *= right; |
| 22 | + * right *= nums[i]; |
| 23 | + * that's it. |
| 24 | +
|
| 25 | + * This could be very well illustrated with this example: [1,2,3,4]*/ |
15 | 26 | public int[] productExceptSelf(int[] nums) {
|
16 | 27 | int n = nums.length;
|
17 | 28 | int[] result = new int[n];
|
18 | 29 | result[0] = 1;
|
19 | 30 | for (int i = 1; i < n; i++) {
|
20 |
| - result[i] = result[i-1]*nums[i-1]; |
| 31 | + result[i] = result[i - 1] * nums[i - 1]; |
21 | 32 | }
|
22 | 33 | int right = 1;
|
23 |
| - for (int i = n-1; i >= 0; i--) { |
| 34 | + for (int i = n - 1; i >= 0; i--) { |
24 | 35 | result[i] *= right;
|
25 | 36 | right *= nums[i];
|
26 | 37 | }
|
|
0 commit comments