File tree Expand file tree Collapse file tree
main/java/com/fishercoder/solutions/firstthousand
test/java/com/fishercoder/firstthousand Expand file tree Collapse file tree Original file line number Diff line number Diff line change 33public 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]
Original file line number Diff line number Diff line change 88
99public 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
You can’t perform that action at this time.
0 commit comments