Given an array of integers that's already sorted in ascending order, find, numbers such, they add up to a Specific target number.
The function twosum should return indices of the numbers such that they add up to the target, where index1 must is Les S than Index2. Please note that your returned answers (both Index1 and INDEX2) is not zero-based.
You may assume this each input would has exactly one solution and you may not use the same element TWIC E.
Input: numbers={2, 7, one, target=9
Output: index1=1, index2=2
One pointer at both ends of the array, looking in the middle.
static public int [ ] twosum ( int [] numbers int target ) {
if (numbers == null || numbers.Length < 1) {
return null;
}
int left = 0;
int right = numbers.Length - 1;
while (left < right) {
if (numbers[left] + numbers[right] > target) {
right--;
} else if (numbers[left] + numbers[right] < target) {
left++;
} else if ( numbers [ left ] + numbers [ right ] == target ) Span class= "PLN" > {
int[] result = { left + 1,right + 1};
return result;
}
}
return null;
}
Null
167. Find two numbers, array sorted two Sum ii-input array is sorted