描述
給定一個(gè)已經(jīng)按升序排列的數(shù)組罚随,找到兩個(gè)數(shù)使他們加起來的和等于特定數(shù)玉工。
函數(shù)應(yīng)該返回這兩個(gè)數(shù)的下標(biāo),index1必須小于index2淘菩。注意返回的值不是 0-based遵班。
注意事項(xiàng)
你可以假設(shè)每個(gè)輸入剛好只有一個(gè)答案
樣例
給定數(shù)組為 [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;
}
}