1212 */
1313public class Problem01 {
1414
15+ /*
16+ This solution is O(n)
17+ */
1518 public static int [] twoSum (int [] numbers , int target ) {
1619 /*
1720 Algorithm:
18- 1. Create a new array with filtering all the numbers less than the target.
19- 2. Iterate over the filtered array to find a pair which sum equal to target
21+ 1. Store all the number and their indexes in a Map
22+ 2. Create a new array with filtering all the numbers less than the target.
23+ 3. Iterate over the filtered array.
24+ 4. For each number find the second number by subtracting it from the target
25+ 5. If Map contains the second number then we have found the pair
26+ 6. Short circuit the loop and return the result.
2027 */
28+ Map <Integer , Integer > numberAndIndex = new HashMap <>();
29+ for (int i = 0 ; i < numbers .length ; i ++) {
30+ numberAndIndex .put (numbers [i ], i );
31+ }
32+
2133 int [] numbersLessThanTarget = Arrays .stream (numbers ).filter (i -> i < target ).toArray ();
2234
2335 for (int i = 0 ; i < numbersLessThanTarget .length - 1 ; i ++) {
24- for ( int j = i + 1 ; j < numbersLessThanTarget . length ; j ++) {
25- if (( numbersLessThanTarget [ i ] + numbersLessThanTarget [ j ]) == target ) {
26- return new int []{ numbersLessThanTarget [ i ], numbersLessThanTarget [ j ]};
27- }
36+ int first = numbersLessThanTarget [ i ];
37+ int second = target - first ;
38+ if ( numberAndIndex . containsKey ( second )) {
39+ return new int []{ i , numberAndIndex . get ( second )};
2840 }
41+
2942 }
3043 return new int [0 ];
3144 }
3245
33- public static int [] twoSumIndexes (int [] numbers , int target ) {
46+
47+ /*
48+ This solution in O(n^2)
49+ */
50+ public static int [] twoSum_2 (int [] numbers , int target ) {
3451 /*
3552 Algorithm:
3653 1. Create a new array with filtering all the numbers less than the target.
@@ -53,4 +70,6 @@ public static int[] twoSumIndexes(int[] numbers, int target) {
5370 }
5471 return new int [0 ];
5572 }
73+
74+
5675}
0 commit comments