167. Two Sum II - Input array is sorted
這是leetCode第167題
題目
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. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
意思是說:
給你一個已經按照升序排序的整數數組,找出兩個數字,它們相加的和等于一個特定的目標數字。
函數twoSum應該返回這兩個數字的索引,且index1必須小于index2。請注意,你的答案中的索引不是基于0開始的。
您可以假設每個輸入都將具有一個解決方案,您可能不會使用相同的元素兩次。
對于數組[2,7,11,15],目標數字9
應該輸出: index1=1,index2=2;
思路
給我們的數組是按升序排列的,那么我們可以這么做:
1.將數組兩端的數字(數組索引分別為0,length-1)相加,與目標數字比較
2.如果和大于目標數字,就將數組索引大的減少1(和就變小了)。
3.如果和小于目標數字,就將數組索引小的加+1(和就變大了)。
4.直到和等于目標數字,輸出此時數組的索引,記得都加1,或者直到索引大的等于索引小的,就輸出[-1,-1]
代碼如下:
/**
* @param {number[]} numbers
* @param {number} target
* @return {number[]}
*/
var twoSum = function(numbers, target) {
var low = 0, high = numbers.length - 1;
var sum = 0;
while (low < high) {
sum = numbers[low] + numbers[high];
if (sum > target) {
high--;
} else if (sum < target) {
low++;
} else {
return [low + 1, high + 1];
}
}
return [-1, -1];
};