Skip to content

Commit 97b8719

Browse files
committed
Solve problem '167) two sum ii - input array is sorted'
1 parent d310ea1 commit 97b8719

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
Given a **1-indexed** array of integers `numbers` that is already **sorted in non-decreasing order**, find two numbers such that they add up to a specific `target` number. Let these two numbers be `numbers[index1]` and `numbers[index2]` where `1 <= index1 < index2 <= numbers.length`.
2+
3+
Return _the indices of the two numbers_, `index1` and `index2`, **added by one** as an integer array `[index1, index2]` of length 2.
4+
5+
The tests are generated such that there is **exactly one solution**. You **may not** use the same element twice.
6+
7+
**Example 1:**
8+
9+
```
10+
Input: numbers = [2,7,11,15], target = 9
11+
Output: [1,2]
12+
Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
13+
```
14+
15+
**Example 2:**
16+
17+
```
18+
Input: numbers = [2,3,4], target = 6
19+
Output: [1,3]
20+
Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].
21+
```
22+
23+
**Example 3:**
24+
25+
```
26+
Input: numbers = [-1,0], target = -1
27+
Output: [1,2]
28+
Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].
29+
```
30+
31+
**Constraints:**
32+
33+
- `2 <= numbers.length <= 3 * 10^4`
34+
- `-1000 <= numbers[i] <= 1000`
35+
- `numbers` is sorted in **non-decreasing order**.
36+
- `-1000 <= target <= 1000`
37+
- The tests are generated such that there is **exactly one solution**.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package main
2+
3+
import "fmt"
4+
5+
func main() {
6+
fmt.Println(twoSum([]int{2, 7, 11, 15}, 9))
7+
fmt.Println(twoSum([]int{2, 3, 4}, 6))
8+
fmt.Println(twoSum([]int{-1, 0}, -1))
9+
}
10+
11+
func twoSum(numbers []int, target int) []int {
12+
i, j := 0, len(numbers)-1
13+
for i < j {
14+
if numbers[i]+numbers[j] == target {
15+
return []int{i + 1, j + 1}
16+
} else if numbers[i]+numbers[j] < target {
17+
i++
18+
} else {
19+
j--
20+
}
21+
}
22+
23+
return nil
24+
}

0 commit comments

Comments
 (0)