Skip to content

Commit 440ebfb

Browse files
add a solution for 238
1 parent 742c858 commit 440ebfb

2 files changed

Lines changed: 23 additions & 0 deletions

File tree

  • src
    • main/java/com/fishercoder/solutions/firstthousand
    • test/java/com/fishercoder/firstthousand

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,26 @@
33
public class _238 {
44

55
public static class Solution1 {
6+
public int[] productExceptSelf(int[] nums) {
7+
int[] left = new int[nums.length];
8+
left[0] = 1;
9+
for (int i = 1; i < left.length; i++) {
10+
left[i] = nums[i - 1] * left[i - 1];
11+
}
12+
int[] right = new int[nums.length];
13+
right[nums.length - 1] = 1;
14+
for (int i = nums.length - 2; i >= 0; i--) {
15+
right[i] = nums[i + 1] * right[i + 1];
16+
}
17+
int[] res = new int[nums.length];
18+
for (int i = 0; i < nums.length; i++) {
19+
res[i] = left[i] * right[i];
20+
}
21+
return res;
22+
}
23+
}
24+
25+
public static class Solution2 {
626
/*
727
* Very straightforward idea: iterate through the array twice:
828
* first time: get res[i] = res[i-1]*nums[i-1]

src/test/java/com/fishercoder/firstthousand/_238Test.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,15 @@
88

99
public class _238Test {
1010
private _238.Solution1 solution1;
11+
private _238.Solution2 solution2;
1112
private static int[] expected;
1213
private static int[] actual;
1314
private static int[] nums;
1415

1516
@BeforeEach
1617
public void setup() {
1718
solution1 = new _238.Solution1();
19+
solution2 = new _238.Solution2();
1820
expected = new int[] {};
1921
actual = new int[] {};
2022
}
@@ -24,6 +26,7 @@ public void test1() {
2426
nums = new int[] {0, 0};
2527
expected = new int[] {0, 0};
2628
actual = solution1.productExceptSelf(nums);
29+
actual = solution2.productExceptSelf(nums);
2730
assertArrayEquals(expected, actual);
2831
}
2932

0 commit comments

Comments
 (0)