牛客网 NC61 两数之和
https://www.nowcoder.com/share/jump/7890810391698077140732
记录:维护哈希表,题目满足,numbers内必有两数相加为target,则可理解为,每次只需要判断target减去当前数,是否能在维护的表内查到。下述代码:
package main
import "fmt"
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param numbers int整型一维数组
* @param target int整型
* @return int整型一维数组
*/
func main() {
fmt.Println(twoSum([]int{-3, 4, 3, 90}, 0))
}
func twoSum(numbers []int, target int) []int {
// write code here
numMap := make(map[int]int, len(numbers))
for i, number := range numbers {
if val, ok := numMap[target-number]; ok {
return []int{val + 1, i + 1}
}
numMap[number] = i
}
return nil
}