因为是已经排好序的array,所以用two pointer从两边往中间逼近,注意最后返回的下标 + 1
1 /** 2 * @param {number[]} numbers 3 * @param {number} target 4 * @return {number[]} 5 */ 6 var twoSum = function(numbers, target) { 7 // corner case 8 if (numbers === undefined || numbers.length < 2) { 9 return [-1, -1]; 10 } 11 12 // normal case 13 let start = 0; 14 let end = numbers.length - 1; 15 while (start < end) { 16 const sum = numbers[start] + numbers[end]; 17 if (sum === target) { 18 return [start + 1, end + 1]; 19 } else if (sum < target) { 20 start++; 21 } else { 22 end--; 23 } 24 } 25 return [-1, -1]; 26 };