Skip to content

Instantly share code, notes, and snippets.

@TealOcean
Last active December 10, 2017 03:57
Show Gist options
  • Save TealOcean/a1b9e44db6289a07e9db7d2d5676e882 to your computer and use it in GitHub Desktop.
Save TealOcean/a1b9e44db6289a07e9db7d2d5676e882 to your computer and use it in GitHub Desktop.
2 Sum Solution
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] indexes = new int[]{-1, -1};
Map<Integer, List<Integer>> contents = new HashMap<>();
/*
Let's record where we find a value in the map.
This safe guards if a value appears twice.
*/
for(int i = 0; i < nums.length; i++) {
int key = nums[i];
/*
Check if we already are holding this key,
if we are not, add it and store where it is.
Otherwise, append the location.
*/
if(contents.containsKey(key)) {
contents.get(key).add(i);
} else {
List<Integer> indexesFound = new ArrayList<>(2);
indexesFound.add(i);
contents.put(key, indexesFound);
}
}
//Now, let's do our search.
for(int i = 0; i < nums.length; i++) {
int valueA = nums[i];
int valueWanted = target - valueA;
//If we find the value we wanted, we're almost done!
boolean found = contents.containsKey(valueWanted);
if (found) {
/*
If it happens to be the same as valueA,
make sure we have more than 1 to work with.
*/
if (valueA == valueWanted && contents.get(valueWanted).size() > 1) {
indexes[0] = i;
indexes[1] = contents.get(valueWanted).get(1);
return indexes;
} else if (valueA != valueWanted) {
indexes[0] = i;
indexes[1] = contents.get(valueWanted).get(0);
return indexes;
}
}
}
return indexes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment