Skip to content

Commit 76571b8

Browse files
aQuaaQua
aQua
authored and
aQua
committed
167 accepted and finish
1 parent b9aa5d7 commit 76571b8

File tree

3 files changed

+83
-0
lines changed

3 files changed

+83
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# [167. Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/)
2+
3+
## 题目
4+
5+
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.
6+
7+
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. Please note that your returned answers (both index1 and index2) are not zero-based.
8+
9+
You may assume that each input would have exactly one solution and you may not use the same element twice.
10+
11+
```
12+
**Input:*** numbers={2, 7, 11, 15}, target=9
13+
***Output:*** index1=1, index2=2
14+
```
15+
16+
17+
## 解题思路
18+
19+
参考 [1.Two Sum](./Algorithms/0001.two-sum)
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package Problem0167
2+
3+
func twoSum(nums []int, target int) []int {
4+
m := make(map[int]int, len(nums))
5+
6+
for i, n := range nums {
7+
if m[target-n] != 0 {
8+
return []int{m[target-n], i + 1}
9+
}
10+
m[n] = i + 1
11+
}
12+
13+
return nil
14+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package Problem0167
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
type question struct {
11+
para
12+
ans
13+
}
14+
15+
// para 是参数
16+
type para struct {
17+
numbers []int
18+
target int
19+
}
20+
21+
// ans 是答案
22+
type ans struct {
23+
one []int
24+
}
25+
26+
func Test_Problem0167(t *testing.T) {
27+
ast := assert.New(t)
28+
29+
qs := []question{
30+
31+
question{
32+
para{
33+
[]int{2, 7, 11, 15},
34+
9,
35+
},
36+
ans{
37+
[]int{1, 2},
38+
},
39+
},
40+
41+
// 如需多个测试,可以复制上方元素。
42+
}
43+
44+
for _, q := range qs {
45+
a, p := q.ans, q.para
46+
fmt.Printf("~~%v~~\n", p)
47+
48+
ast.Equal(a.one, twoSum(p.numbers, p.target), "输入:%v", p)
49+
}
50+
}

0 commit comments

Comments
 (0)