# Leetcode - Two Sum II - Input array is sorted

violet posted @ Mar 03, 2020 06:26:36 AM in 算法 with tags Algorithm 算法 2sum Golang ruby , 287 阅读

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.

Note:

• You may assume that each input would have exactly one solution and you may not use the same element twice.

Example:

```Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.```

Since the array is sorted, use two pointers to do iteration. Left pointer is from the beginning, right pointer is from the end. Sum up left and right and compare sum with target. If the target is equal to sum, return left+1 and right+1

```func twoSum(numbers []int, target int) []int {
left := 0
right := len(numbers)-1
for left < right {
sum := numbers[left] + numbers[right]
if sum == target {
return []int{left+1, right+1}
}
if sum > target {
right--
}
if sum < target {
left++
}
}
return nil
}```

```# @param {Integer[]} numbers
# @param {Integer} target
# @return {Integer[]}

def two_sum numbers, target
left = 0
right = numbers.length - 1
while left < right
sum = numbers[left] + numbers[right]
if sum == target
return [left+1, right+1]
end
if sum < target
left += 1
else
right -= 1
end
end
end
``` ELite Delhi Escorts 说:
Feb 10, 2022 07:21:31 PM

Individuals start offering fitting remarks on your remark, and along these lines, you get more popular through free blog remarking destinations. (输入验证码)
or Ctrl+Enter