-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtwosum.go
58 lines (53 loc) · 1.05 KB
/
twosum.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
52
53
54
55
56
57
58
package array
// https://leetcode-cn.com/problems/two-sum/
// nums = [2, 7, 11, 15], target = 9 -> [0, 1]
// traverse twice
func twoSum(nums []int, target int) []int {
if nums == nil {
return nil
}
// key is num, value is index
hashmap := make(map[int]int)
for index, num := range nums {
hashmap[num] = index
}
// make a slice
indexArray := make([]int, 2)
for index, num := range nums {
find, ok := hashmap[target-num]
// not find
if !ok {
continue
}
// find one, but not itself
if find != index {
indexArray[0] = index
indexArray[1] = find
break
}
}
return indexArray
}
func twoSumWithOnceTraversal(nums []int, target int) []int {
if nums == nil {
return nil
}
// key is num, value is index
hashmap := make(map[int]int)
// make a slice
indexArray := make([]int, 2)
for index, num := range nums {
find, ok := hashmap[target-num]
if ok {
// find one, but not itself
if find != index {
indexArray[0] = find
indexArray[1] = index
break
}
} else {
hashmap[num] = index
}
}
return indexArray
}