Skip to content

Commit d38ae97

Browse files
edit 238
1 parent fa2be89 commit d38ae97

File tree

1 file changed

+19
-8
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+19
-8
lines changed

src/main/java/com/fishercoder/solutions/_238.java

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,37 @@
11
package com.fishercoder.solutions;
22

33
/**
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].
910
1011
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.)
1214
*/
15+
1316
public class _238 {
1417

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]*/
1526
public int[] productExceptSelf(int[] nums) {
1627
int n = nums.length;
1728
int[] result = new int[n];
1829
result[0] = 1;
1930
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];
2132
}
2233
int right = 1;
23-
for (int i = n-1; i >= 0; i--) {
34+
for (int i = n - 1; i >= 0; i--) {
2435
result[i] *= right;
2536
right *= nums[i];
2637
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy