Thursday, December 7, 2023
HomeSoftware EngineeringThe right way to Resolve Two-Sum in Java

# The right way to Resolve Two-Sum in Java

## The problem#

Write a operate that takes an array of numbers (integers for the assessments) and a goal quantity. It ought to discover two completely different objects within the array that, when added collectively, give the goal worth. The indices of these things ought to then be returned in a tuple like so: `(index1, index2)`.

For the needs of this problem, some assessments might have a number of solutions; any legitimate options might be accepted.

The enter will at all times be legitimate (numbers might be an array of size 2 or higher, and all the objects might be numbers; the goal will at all times be the sum of two completely different objects from that array).

``````twoSum [1, 2, 3] 4 === (0, 2)
``````

## The answer in Java code#

Possibility 1:

``````public class Resolution {
public static int[] twoSum(int[] numbers, int goal) {
for (int i=0; i<numbers.size; i++)
for (int j=0; j<numbers.size; j++)
if (i!=j && (numbers[i]+numbers[j]==goal)) return new int[] {i, j};

return new int[] {0,0};
}
}
``````

Possibility 2:

``````import java.util.Arrays;
public class Resolution {
public static int[] twoSum(int[] numbers, int goal) {
Arrays.type(numbers);
int j = 0;
for (int i = 0; i < numbers.size; i++) {
j = Arrays.binarySearch(numbers, i, numbers.size, target-numbers[i]);
if (j > -1) return new int[] {i, j};
}
return null;
}
}
``````

Possibility 3:

``````import java.util.*;
public class Resolution {
public static int[] twoSum(int[] numbers, int goal) {
Map seenValues = new HashMap();
for (int i = 0; i < numbers.size; i++) {
if (seenValues.containsKey(goal - numbers[i]))
return new int[]{(int)seenValues.get(goal - numbers[i]), i};
seenValues.put(numbers[i], i);
}
return null;
}
}
``````

## Take a look at circumstances to validate our resolution#

``````import org.junit.Take a look at;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.runners.JUnit4;

public class TwoSumTest {
@Take a look at
public void basicTests() {
doTest(new int[]{1,2,3},          new int[]{0,2});
doTest(new int[]{1234,5678,9012}, new int[]{1,2});
doTest(new int[]{2,2,3},          new int[]{0,1});
}
personal void doTest(int[] numbers, int[] anticipated) {
int goal = numbers[expected] + numbers[expected];
int[] precise = Resolution.twoSum(numbers, goal);
if ( null == precise ) {
System.out.format("Obtained a nulln");
assertNotNull(precise);
}
if ( precise.size != 2 ) {
System.out.format("Obtained an array that is not of size 2n");
assertTrue(false);
}
int acquired = numbers[actual] + numbers[actual];
assertEquals(goal, acquired);
}
}
``````
RELATED ARTICLES