Skip to content

Commit 81e35ff

Browse files
committed
add problem 238
1 parent 1b1dcf1 commit 81e35ff

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package io.github.juchanei.leetcodeJava;
2+
3+
import org.junit.Assert;
4+
import org.junit.Test;
5+
6+
public class ProductOfArrayExceptSelf {
7+
public int[] productExceptSelf(int[] nums) {
8+
int[] productsFromLeft = new int[nums.length];
9+
productsFromLeft[0] = 1;
10+
for (int i = 1; i < nums.length; i++) {
11+
productsFromLeft[i] = productsFromLeft[i - 1] * nums[i - 1];
12+
}
13+
14+
int[] productsFromRight = new int[nums.length];
15+
productsFromRight[nums.length - 1] = 1;
16+
for (int i = nums.length - 2; 0 <= i; i--) {
17+
productsFromRight[i] = productsFromRight[i + 1] * nums[i + 1];
18+
}
19+
20+
int[] ret = new int[nums.length];
21+
for (int i = 0; i < nums.length; i++) {
22+
ret[i] = productsFromLeft[i] * productsFromRight[i];
23+
}
24+
25+
return ret;
26+
}
27+
28+
public static class UnitTest {
29+
private ProductOfArrayExceptSelf poes = new ProductOfArrayExceptSelf();
30+
31+
@Test()
32+
public void example1() {
33+
int[] input = { 1, 2, 3, 4 };
34+
int[] output = { 24, 12, 8, 6 };
35+
Assert.assertArrayEquals(output, poes.productExceptSelf(input));
36+
}
37+
}
38+
}

0 commit comments

Comments
 (0)