leetcode 1. 两数之和

题解

哈希表保存位置

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func twoSum(nums []int, target int) []int {
res := make([]int, 2)
hash := make(map[int]int)
for i, v := range nums {
hash[v] = i
}
for i, v := range nums {
if j, ok := hash[target-v]; ok && j != i {
res[0] = i
res[1] = j
break
}
}
return res
}