Created
October 2, 2018 18:21
-
-
Save hsaputra/d61f083fea2d6c15ddb588a47b956c70 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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