Two Sum
Given an array of integers, find two numbers such that they add up to a specific target number.
- Time: O(n)
- Space: O(1)
public int[] twoSum(int[] nums, int target) {
int[] ret = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
ret[0] = map.get(target - nums[i]);
ret[1] = i;
break;
}
map.put(nums[i], i);
}
return ret;
}