描述
給定一個已經按升序排列的數組,找到兩個數使他們加起來的和等于特定數。
函數應該返回這兩個數的下標,index1必須小于index2。注意返回的值不是 0-based。
注意事項
你可以假設每個輸入剛好只有一個答案
樣例
給定數組為 [2,7,11,15] ,target = 9
返回 [1,2]
代碼
public class Solution {
/*
* @param nums: an array of Integer
* @param target: target = nums[index1] + nums[index2]
* @return: [index1 + 1, index2 + 1] (index1 < index2)
*/
public int[] twoSum(int[] nums, int target) {
// 異常情況返回什么值是事先約定好的,所以寫return new int[2]或null一樣
if (nums == null || nums.length == 0) {
return null;
}
int left = 0, right = nums.length - 1;
while (left < right) {
if (nums[left] + nums[right] == target) {
int[] results = new int[] {left + 1, right + 1};
return results;
}
if (nums[left] + nums[right] < target) {
left++;
} else {
right--;
}
}
return null;
}
}