Created
September 14, 2014 22:45
-
-
Save sopherwang/7bdb6dc9f44d6c67c7dd to your computer and use it in GitHub Desktop.
Two Sum
This file contains 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
public int[] twoSum(int[] numbers, int target) | |
{ | |
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); | |
for (int i = 0; i < numbers.length; i++) | |
{ | |
if (map.get(target - numbers[i]) != null) | |
{ | |
if (map.get(target - numbers[i]) <= i) | |
{ | |
return new int[] { map.get(target - numbers[i]) + 1, i + 1 }; | |
} | |
else | |
{ | |
return new int[] { i + 1, map.get(target - numbers[i]) + 1 }; | |
} | |
} | |
map.put(numbers[i], i); | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment