Skip to content

Commit b33e358

Browse files
author
XianCH
committed
add two sum and test
1 parent 107f4e3 commit b33e358

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

Diff for: 0001_two_sum.go

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package leetcode
2+
3+
func Twonum(nums []int, target int) []int {
4+
m := make(map[int]int)
5+
for i := 0; i < len(nums); i++ {
6+
another := target - nums[i]
7+
if _, ok := m[another]; ok {
8+
return []int{m[another], i}
9+
}
10+
m[nums[i]] = i
11+
}
12+
return nil
13+
}
14+
15+
// Given nums = [2, 7, 11, 15], target = 9,
16+
//
17+
// Because nums[0] + nums[1] = 2 + 7 = 9,
18+
// return [0, 1]

Diff for: 0001_two_sum_test.go

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package leetcode
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
func TestTwonum(t *testing.T) {
9+
tests := []struct {
10+
nums []int
11+
target int
12+
want []int
13+
}{
14+
{[]int{2, 7, 6, 2}, 9, []int{0, 1}},
15+
{[]int{3, 2, 4}, 6, []int{1, 2}},
16+
{[]int{3, 3}, 6, []int{0, 1}},
17+
}
18+
19+
for _, tt := range tests {
20+
got := Twonum(tt.nums, tt.target)
21+
if !reflect.DeepEqual(got, tt.want) {
22+
t.Errorf("Twonum(%v,%d)=%v,want %v", tt.nums, tt.target, got, tt.want)
23+
}
24+
}
25+
}

0 commit comments

Comments
 (0)