Skip to content

Commit 174b47c

Browse files
committed
Solve 'Two Sum'
1 parent 04dabd9 commit 174b47c

File tree

3 files changed

+112
-0
lines changed

3 files changed

+112
-0
lines changed

two-sum/spec.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# 1. Two Sum
2+
3+
<https://leetcode.com/problems/two-sum/>
4+
5+
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
6+
7+
You may assume that each input would have exactly one solution, and you may not use the same element twice.
8+
9+
Example:
10+
11+
```text
12+
Given nums = [2, 7, 11, 15], target = 9,
13+
14+
Because nums[0] + nums[1] = 2 + 7 = 9,
15+
return [0, 1].
16+
```

two-sum/sum.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package twosum
2+
3+
func twoSum(nums []int, target int) []int {
4+
length := len(nums)
5+
if length == 0 {
6+
return nil
7+
}
8+
if length == 1 {
9+
if nums[0] == target {
10+
return []int{0}
11+
}
12+
}
13+
14+
for i := 0; i < length; i++ {
15+
a := nums[i]
16+
for j := i + 1; j < length; j++ {
17+
b := nums[j]
18+
19+
sum := a + b
20+
21+
if sum == target {
22+
return []int{i, j}
23+
}
24+
}
25+
}
26+
27+
return nil
28+
}

two-sum/sum_test.go

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package twosum
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
func Test_twoSum(t *testing.T) {
10+
type args struct {
11+
nums []int
12+
target int
13+
}
14+
15+
tests := []struct {
16+
name string
17+
args args
18+
want []int
19+
}{
20+
{
21+
name: "sum exist",
22+
args: args{
23+
nums: []int{2, 7, 11, 15},
24+
target: 9,
25+
},
26+
want: []int{0, 1},
27+
},
28+
{
29+
name: "empty slice",
30+
args: args{
31+
nums: nil,
32+
target: 9,
33+
},
34+
want: nil,
35+
},
36+
{
37+
name: "one element",
38+
args: args{
39+
nums: []int{9},
40+
target: 9,
41+
},
42+
want: []int{0},
43+
},
44+
{
45+
name: "no target sum",
46+
args: args{
47+
nums: []int{9,2,99},
48+
target: 1000,
49+
},
50+
want: nil,
51+
},
52+
{
53+
name: "3,2,4",
54+
args: args{
55+
nums: []int{3,2,4},
56+
target: 6,
57+
},
58+
want: []int{1,2},
59+
},
60+
}
61+
62+
for _, tt := range tests {
63+
t.Run(tt.name, func(t *testing.T) {
64+
got := twoSum(tt.args.nums, tt.args.target)
65+
assert.Equal(t, tt.want, got)
66+
})
67+
}
68+
}

0 commit comments

Comments
 (0)