# Leetcode - Two Sum II - Input array is sorted

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

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.

10thmodelpaper2021.i 说:
May 03, 2023 09:25:13 PM

10th Board Model Paper 2023 Aspirants who had Registered for the Board 10th Class Exam can Download the Previous Paper When Board Announces the Dates to Download the Question Paper. 10thmodelpaper2021.in Board Question Papers will be Provided Very Soon Through Online Mode and all the Applicants Should Visit the Official Page Regularly for More Information Regarding Previous Paper, Examination Date. Check the Below Provided Details for More Information About the Board Model Paper.

(输入验证码)
or Ctrl+Enter