LeetCode Q 167 - Two Sum II - Input array is sorted
Given an array of integers that is already sorted in ascending order, 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.
Solution
Method : Two pointers
Code:
public int[] twoSum(int[] numbers, int target) {
int idx1 = 0, idx2 = numbers.length - 1;
while (numbers[idx1] + numbers[idx2] != target) {
if (numbers[idx1] + numbers[idx2] > target)
idx2--;
else
idx1++;
}
return new int[]{idx1 + 1, idx2 + 1};
}