-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path01_two_sum_test.go
47 lines (42 loc) · 1.04 KB
/
01_two_sum_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package main
import (
"github.com/smartystreets/goconvey/convey"
"testing"
)
// 两数之和 https://leetcode.cn/problems/two-sum/description/?envType=study-plan-v2&envId=top-100-liked
func TestTwoSum(t *testing.T) {
convey.Convey("two sums ", t, func() {
testCase := []struct {
input []int
target int
expected []int
}{
{
[]int{2, 7, 11, 15}, 9, []int{0, 1},
},
{
[]int{3, 2, 4}, 6, []int{1, 2},
},
{
[]int{3, 3}, 6, []int{0, 1},
},
}
for _, tst := range testCase {
ret := twoSum(tst.input, tst.target)
convey.So(ret, convey.ShouldEqual, tst.expected)
}
})
}
// 不推荐行为:两个循环暴力枚举
// 推荐行为:hash
func twoSum(nums []int, target int) []int {
// 存储出现过的结果
hashTable := map[int]int{} // key为元素,value为索引
for i, x := range nums {
if p, ok := hashTable[target-x]; ok {
return []int{p, i} // 小的索引在前面
}
hashTable[x] = i // 注意这在判断之后
}
return nil // 题目保证一定有解,代码不会执行到这里
}