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.
Notice
You may assume that each input would have exactly one solution
Example
numbers=[2, 7, 11, 15], target=9
return [1, 2]
Solution: Two pointer, one from start, one from end. We need to keep original index so we create a new class to do this, or you can copy the elements to a new array.
public int[] twoSum(int[] numbers, int target) {
// write your code here
if(numbers == null || numbers.length == 0) {
return new int[0];
}
int[] res = new int[2];
Number[] arr = new Number[numbers.length];
for(int i = 0; i < numbers.length; i++) {
arr[i] = new Number(numbers[i], i);
}
Arrays.sort(arr, new NumComparator());
int left = 0, right = numbers.length - 1;
while(left < right) {
int sum = arr[left].x + arr[right].x;
if(sum == target) {
res[0] = arr[left].index + 1;
res[1] = arr[right].index + 1;
Arrays.sort(res);
return res;
}
else if(sum < target) {
left++;
}
else {
right--;
}
}
return new int[0];
}
class Number {
int x;
int index;
public Number(int x, int index) {
this.x = x;
this.index = index;
}
}
class NumComparator implements Comparator<Number> {
@Override
public int compare(Number n1, Number n2) {
return n1.x - n2.x;
}
}
Another solution is use HashMap.
public int[] twoSum(int[] numbers, int target) {
if(numbers == null || numbers.length == 0) {
return new int[0];
}
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] res = new int[2];
for(int i = 0; i < numbers.length; i++) {
if(!map.containsKey(numbers[i])) {
map.put(target - numbers[i], i);
}
else {
res[0] = map.get(numbers[i]) + 1;
res[1] = i + 1;
Arrays.sort(res);
return res;
}
}
return res;
}