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.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
Output: index1=1, index2=2
Naive Way: In Two Sum, the array is not sorted. Thus, we need extra O(n) space to store visited ones. This time, the array is sorted, leading me to think about the 3-sum method algorithm. With two pointers, we can do it in O(1) space.
public int[] twoSum2(int numbers[], int target){
int[] rslt = {-1,-1};
int low = 0, high = numbers.length-1;
while(low < high){
if(numbers[low]+numbers[high] == target){
rslt[0] = low+1;
rslt[1] = high+1;
break;
}
if(numbers[low]+numbers[high] > target)
high--;
else
low++;
}
return rslt;
}
No comments:
Post a Comment