AlgoMaster Logo

Two Sum II - Input Array Is Sorted

numbers=[2, 7, 11, 15],target=9
1public int[] twoSum(int[] numbers, int target) {
2    int left = 0;
3    int right = numbers.length - 1;
4
5    while (left < right) {
6        int sum = numbers[left] + numbers[right];
7
8        if (sum == target) {
9            return new int[]{left + 1, right + 1};
10        } else if (sum < target) {
11            left++;
12        } else {
13            right--;
14        }
15    }
16
17    return new int[]{};
18}
0 / 7
271115