Two Sum
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are NOT zero-based.
Example
numbers=[2, 7, 11, 15], target=9
return [1, 2]
Notes:
- HashMap: value to index map
- Two Pointers: need sort, still need to use HashMap map the index
public int[] twoSum(int[] numbers, int target) {
if (numbers == null) {
return null;
}
int[] result = new int[2];
Map<Integer, Integer> v2IMap = new HashMap<>();
for (int i = 0; i < numbers.length; ++i) {
if (v2IMap.containsKey(target-numbers[i])) {
result[0] = v2IMap.get(target-numbers[i])+1;
result[1] = i+1;
return result;
} else {
v2IMap.put(numbers[i], i);
}
}
return null;
}
public int[] twoSum(int[] nums, int target) {
if (nums == null) {
return new int[0];
}
Map<Integer, List<Integer>> map = new HashMap<>();
for (int i = 0; i < nums.length; ++i) {
if (!map.containsKey(nums[i])) {
map.put(nums[i], new ArrayList<Integer>());
}
map.get(nums[i]).add(i);
}
Arrays.sort(nums);
int i = 0;
int j = nums.length-1;
while(i < j) {
if (nums[i] + nums[j] == target) {
int i1 = map.get(nums[i]).get(0);
int i2 = map.get(nums[j]).get(0);
if (i2 == i1) {
i2 = map.get(nums[j]).get(1);
}
return new int[]{Math.min(i1, i2)+1, Math.max(i1, i2)+1};
}
if (nums[i] + nums[j] > target) {
j--;
} else {
i++;
}
}
return new int[0];
}