Q:given an array of integers that's already sorted in ascending order, find, numbers such, they add up t o 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.
Input:numbers={2, 7, one, A, target=9
Output:index1=1, index2=2
Both Sum ii-input array is sorted
public class Solution2 {
Public int[] Twosum (int[] numbers, int target) {
for (int i = 0; i < numbers.length; i++) {
Int J = bsearch (numbers, target-numbers[i], i + 1);
if (j! =-1) {
return new int[] {i+1, j+1};
}
}
throw new IllegalArgumentException ("No, sum solution!");
}
public int bsearch (int[] A, int key, int start) {
int L = a.length-1;
while (start <= l) {
int m = (start + L)/2;
if (A[m] < key) {
start = m + 1;
} else if (A[m] > key) {
L = m-1;
} else {
return m;
}
}
return-1;
}
}
Double Sum Ii-input Array is sorted (leetcode167)-Solution1