-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path1.go
51 lines (46 loc) · 905 Bytes
/
1.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
48
49
50
51
package main
import "fmt"
func main() {
fmt.Println("vim-go")
nums := []int{2, 7, 11, 15}
target := 9
result := twoSum(nums, target)
fmt.Println(result)
}
func twoSum(nums []int, target int) []int {
m := make(map[int]int)
for i := 0; i < len(nums); i++ {
num := nums[i]
peer := target - num
if peerIdx, ok := m[peer]; ok {
return []int{peerIdx, i}
}
m[num] = i
}
return nil
}
func twoSum_02(nums []int, target int) []int {
m := make(map[int]int)
for i := 0; i < len(nums); i++ {
m[nums[i]] = i
}
for i := 0; i < len(nums); i++ {
num := nums[i]
peer := target - num
peerIdx, ok := m[peer]
if ok && peerIdx != i {
return []int{i, peerIdx}
}
}
return nil
}
func twoSum_01(nums []int, target int) []int {
for i := 0; i < len(nums); i++ {
for j := i + 1; j < len(nums); j++ {
if nums[i]+nums[j] == target {
return []int{i, j}
}
}
}
return nil
}