Since the internship after a long time did not do algorithm questions, immediately to school recruit, restart the brush problem
Given an array of integers it already sorted in ascending order, find two numbers such this they add up to a specific Target number.
The function twosum should return indices of the two numbers such this they add up to the target where index1 must is Les S than Index2. Please note this your returned answers (both INDEX1 and index2) are not zero-based.
You may assume the solution element same of each input would have exactly one twice and.
Input:numbers={2, 7, one, target=9
Output:index1=1, index2=2
public class P167_twosumii_inputarrayissorted {/* solution one/public int[] Twosum (int[] numbers, int target)
{int L = 0, r = numbers.length-1;
while (L < R) {if (Numbers[l] + numbers[r] = = target) {int[] res = {L + 1, r + 1};
return res;
else if (Numbers[l] + numbers[r] > target) r--;
else l++;
} throw new RuntimeException ("The input has no solution"); }/* Solution two/public int[] TWOSUM1 (int[] numbers, int target) {if (numbers = null | | numbers.len
Gth = = 0) return null;
int[] res = new INT[2];
int index; for (int i = 0; i < numbers.length i++) {index = BinarySearch (numbers, target-numbers[i], i + 1, number
S.LENGTH-1);
if (index!=-1) {Res[0] = i + 1;
RES[1] = index + 1;
return res; } return res;
private int BinarySearch (int[] arr, int k, int start, int end) {int mid;
int left = start, right = end;
While [left <= right] {mid = left + (right-left)/2;
if (Arr[mid] > k) right = Mid-1;
else if (Arr[mid] < K) left = mid + 1;
else return mid;
} return-1;
@Test public void Test1 () {int[] arr = {2, 3, 4};
int[] res = twosum (arr, 6);
for (int i = 0; i < res.length i++) {System.out.println (res[i]); }
}
}