The problem
Write a perform that takes an array of numbers (integers for the exams) and a goal quantity. It ought to discover two completely different gadgets 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 exams might have a number of solutions; any legitimate options shall be accepted.
The enter will all the time be legitimate (numbers shall be an array of size 2 or larger, and all the gadgets shall be numbers; the goal will all the time be the sum of two completely different gadgets 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 answer
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});
}
non-public void doTest(int[] numbers, int[] anticipated) {
int goal = numbers[expected[0]] + numbers[expected[1]];
int[] precise = Resolution.twoSum(numbers, goal);
if ( null == precise ) {
System.out.format("Acquired a nulln");
assertNotNull(precise);
}
if ( precise.size != 2 ) {
System.out.format("Acquired an array that is not of size 2n");
assertTrue(false);
}
int obtained = numbers[actual[0]] + numbers[actual[1]];
assertEquals(goal, obtained);
}
}