Skip to content

Instantly share code, notes, and snippets.

@javabuddy
Created October 13, 2020 15:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javabuddy/4694243da1934a68e421dc8002b7a128 to your computer and use it in GitHub Desktop.
Save javabuddy/4694243da1934a68e421dc8002b7a128 to your computer and use it in GitHub Desktop.
import org.junit.Assert;
/**
* My solution of classical two sum problem in Java.
Problem - Given an array of
* integers, find two numbers such that they add up to
a specific target number.
*
* The method twoSum should return indices of the two numbers such that they add
* up to the target, where index1 must be less than index2.
Please note that
* your returned answers (both index1 and index2) are not zero-based.
*
* Note: You may assume that each input would have exactly one solution.
*
* Example [2,7,11,15], 9 -> [1,2]
*
* @author Javin Paul
*
*/
public class TwoSum {
public static int[] twoSum(int[] input, int target) {
for (int i = 0; i < input.length; i++) {
int first = input[i];
for (int j = i + 1; j < input.length; j++) {
int second = input[j];
int total = first + second;
if (total == target) {
return new int[] { i + 1, j + 1 };
}
}
}
return null;
}
public static void main(String args[]) {
// return pairs which adds to 29 in given array
Assert.assertArrayEquals(new int[] { 1, 2 },
twoSum(new int[] { 12, 17, 21, 25 }, 29));
}
}