Optimized for runtime.
Time O(n)
Memory O(n)
class Solution { public int[] twoSum(int[] nums, int target) { int[] ret = new int[2]; HashMap < Integer, Integer > map = new HashMap < Integer, Integer > (); for (int i = 0; i < nums.length; i++) { if (map.get(nums[i]) != null) { ret[0] = map.get(nums[i]); ret[1] = i; return ret; } map.put(target - nums[i], i); } return ret; } }