//給定一個已按照升序排列 的有序數組,找到兩個數使得它們相加之和等於目標數。
//
// 函數應該返回這兩個下標值 index1 和 index2,其中 index1 必須小於 index2。
//
// 說明:
//
//
// 返回的下標值(index1 和 index2)不是從零開始的。
// 你可以假設每個輸入只對應唯一的答案,而且你不可以重複使用相同的元素。
//
//
// 示例:
//
// 輸入: numbers = [2, 7, 11, 15], target = 9
//輸出: [1,2]
//解釋: 2 與 7 之和等於目標數 9 。因此 index1 = 1, index2 = 2 。
// Related Topics 數組 雙指針 二分查找
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int[] twoSum(int[] numbers, int target) {
int left = 0;
int right = numbers.length-1;
//其中 index1 必須小於 index2。
while (left < right) {
int sum = numbers[left] + numbers[right];
if (sum == target) {
return new int[]{left + 1, right + 1};
} else if (sum < target) {
left++;
} else if (sum > target) {
right--;
}
}
return new int[]{-1, -1};
}
}
//leetcode submit region end(Prohibit modification and deletion)