``````输入: numbers = [2, 7, 11, 15], target = 9

### 题解

``````/**
* @param {number[]} numbers
* @param {number} target
* @return {number[]}
*/
var twoSum = function(numbers, target) {
for (let i = 0; i < numbers.length; i++) {
const index = binarySearch(numbers, target - numbers[i])
if (typeof(index) === 'number') {
return [i + 1, index + 1]
}
}
}

var binarySearch = function(arr, value) {
let left = 0
let right = arr.length - 1

while (left <= right) {
const mid = left + Math.ceil((right - left) / 2)
if (arr[mid] === value) {
return mid
} else if (arr[mid] < value) {
left = mid + 1
} else if (arr[mid] > value) {
right = mid - 1
}
}
return null
}``````

``````/**
* @param {number[]} numbers
* @param {number} target
* @return {number[]}
*/
var twoSum = function(numbers, target) {
let left = 0
let right = numbers.length - 1

while (left <= right) {
const sum = numbers[left] + numbers[right]
if (sum === target) {
return [left + 1, right + 1]
} else if (sum > target) {
right--
} else if (sum < target) {
left++
}
}
}``````

125、344、345