Skip to content

Instantly share code, notes, and snippets.

@Jun711
Last active February 21, 2019 17:30
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 Jun711/ca8c9c7c25acf716e4ebcda96263ec6e to your computer and use it in GitHub Desktop.
Save Jun711/ca8c9c7c25acf716e4ebcda96263ec6e to your computer and use it in GitHub Desktop.
TestDome TwoSum
import java.util.Map;
import java.util.HashMap;
public class TwoSum {
private static Map<Integer, Integer> numPositions;
public static int[] findTwoSum(int[] list, int sum) {
numPositions = new HashMap<>();
System.out.println("sum: " + sum);
if (list == null || list.length <= 1)
return null;
for (int i = 0; i < list.length; i++) {
int toRetrieve = sum - list[i];
if (numPositions.containsKey(toRetrieve)) {
if (toRetrieve + list[i] == sum)
return new int[]{numPositions.get(toRetrieve), i};
}
numPositions.put(list[i], i);
}
return null;
}
public static void main(String[] args) {
int[] indices = findTwoSum(new int[] { 1, 3, 5, 3, 9}, 5);
int[] indices2 = findTwoSum(new int[] { 1, 3, 5, 3, 9}, 6);
int[] indices3 = findTwoSum(new int[] { 1, 2}, 5);
if (indices != null) {
System.out.println("indices: " + indices[0] + " " + indices[1]);
}
if (indices2 != null) {
System.out.println("indices2: " + indices2[0] + " " + indices2[1]);
}
if (indices3 != null) {
System.out.println("indices3: " + indices3[0] + " " + indices3[1]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment