Skip to content

Commit 4f26ee1

Browse files
committed
Add Two Sum solution
1 parent 4f40521 commit 4f26ee1

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

two_sum.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package main
2+
3+
import "fmt"
4+
5+
func twoSum(nums []int, target int) []int {
6+
var numMap = map[int]int{}
7+
var result = []int{}
8+
for i, num := range nums {
9+
10+
if j, ok := numMap[num]; ok {
11+
result = []int{j, i};
12+
}
13+
14+
var complement = target - num
15+
numMap[complement] = i
16+
17+
if (len(result) > 2) {
18+
return result
19+
}
20+
}
21+
22+
return result
23+
}
24+
25+
func main() {
26+
nums := []int{2, 7, 11, 15}
27+
result := twoSum(nums, 9)
28+
fmt.Printf("%#v\n", result)
29+
}

0 commit comments

Comments
 (0)