Skip to content

Instantly share code, notes, and snippets.

@hsaputra
Created October 2, 2018 18:21
Show Gist options
  • Save hsaputra/d61f083fea2d6c15ddb588a47b956c70 to your computer and use it in GitHub Desktop.
Save hsaputra/d61f083fea2d6c15ddb588a47b956c70 to your computer and use it in GitHub Desktop.
class Solution {
public int[] twoSum(int[] nums, int target) {
// Tests:
// 1. Empty array
// 2. 1 element
// 3. Negative vs positive
// Exactly One solution
if (nums == null || nums.length == 0) {
return null;
}
Map<Integer, Integer> numToIndex = new HashMap<Integer, Integer>();
final int len = nums.length;
for (int i = 0; i < len; i++) {
int num = nums[i];
int complement = target - num;
if (numToIndex.containsKey(complement)) {
return new int[] {numToIndex.get(complement), i};
}
numToIndex.put(num, i);
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment