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
意思是說(shuō):
給你一個(gè)已經(jīng)按照升序排序的整數(shù)數(shù)組,找出兩個(gè)數(shù)字,它們相加的和等于一個(gè)特定的目標(biāo)數(shù)字。
函數(shù)twoSum應(yīng)該返回這兩個(gè)數(shù)字的索引,且index1必須小于index2。請(qǐng)注意,你的答案中的索引不是基于0開(kāi)始的。
您可以假設(shè)每個(gè)輸入都將具有一個(gè)解決方案,您可能不會(huì)使用相同的元素兩次。
對(duì)于數(shù)組[2,7,11,15],目標(biāo)數(shù)字9
應(yīng)該輸出: index1=1,index2=2;
思路
給我們的數(shù)組是按升序排列的,那么我們可以這么做:
1.將數(shù)組兩端的數(shù)字(數(shù)組索引分別為0,length-1)相加,與目標(biāo)數(shù)字比較
2.如果和大于目標(biāo)數(shù)字,就將數(shù)組索引大的減少1(和就變小了)。
3.如果和小于目標(biāo)數(shù)字,就將數(shù)組索引小的加+1(和就變大了)。
4.直到和等于目標(biāo)數(shù)字,輸出此時(shí)數(shù)組的索引,記得都加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];
};