Skip to content

Commit baa8aad

Browse files
committed
add leetcode task 167
1 parent 327187b commit baa8aad

File tree

4 files changed

+73
-0
lines changed

4 files changed

+73
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -389,6 +389,8 @@
389389

390390
[155. Min Stack](leetcode/155)
391391

392+
[167. Two Sum II - Input Array Is Sorted](leetcode/167)
393+
392394
[328. Odd Even Linked List](leetcode/328)
393395

394396
[347. Top K Frequent Elements](leetcode/347)

leetcode/167/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# 167. Two Sum II - Input Array Is Sorted
2+
3+
See more about problem: [Click](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/)

leetcode/167/solution.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package main
2+
3+
func twoSum(numbers []int, target int) []int {
4+
hMap := make(map[int]int)
5+
6+
for i := 0; i < len(numbers); i++ {
7+
if j, ok := hMap[target-numbers[i]]; ok {
8+
return []int{j + 1, i + 1}
9+
}
10+
hMap[numbers[i]] = i
11+
}
12+
13+
return nil
14+
}

leetcode/167/solution_test.go

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"reflect"
6+
"testing"
7+
)
8+
9+
type TestItemInput struct {
10+
arr []int
11+
target int
12+
}
13+
14+
type TestItem struct {
15+
input TestItemInput
16+
output []int
17+
}
18+
19+
func TestTask(t *testing.T) {
20+
for i, v := range generateTasks() {
21+
t.Run(fmt.Sprintf("Test %d", i+1), func(t *testing.T) {
22+
res := twoSum(v.input.arr, v.input.target)
23+
if !reflect.DeepEqual(res, v.output) {
24+
t.Errorf("Wrong test.\nOutput: \n%v \nExpected: \n%v", res, v.output)
25+
}
26+
})
27+
}
28+
}
29+
30+
func generateTasks() []TestItem {
31+
return []TestItem{
32+
{
33+
input: TestItemInput{
34+
arr: []int{2, 7, 11, 15},
35+
target: 9,
36+
},
37+
output: []int{1, 2},
38+
},
39+
{
40+
input: TestItemInput{
41+
arr: []int{2, 3, 4},
42+
target: 6,
43+
},
44+
output: []int{1, 3},
45+
},
46+
{
47+
input: TestItemInput{
48+
arr: []int{-1, 0},
49+
target: -1,
50+
},
51+
output: []int{1, 2},
52+
},
53+
}
54+
}

0 commit comments

Comments
 (0)