package main
import "fmt"
// an number array and the target
func FindTwoSumNums(numbers []int, n int, target int) (pos1 int, pos2 int) {
// key: this number
// value: the position of this number
var hashmap = make(map[int] int)
for i := 0; i < n; i++ {
var sub = target - numbers[i]
pos, ok := hashmap[sub]
if ok && sub != numbers[i] {
return i, pos
}
hashmap[ numbers[i] ] = i
}
return -1, -1
}
func FindTwoSumNumsHelper(numbers []int, n int, target int) {
p1, p2 := FindTwoSumNums(numbers, n, target)
if p1 != -1 && p2 != -1 {
fmt.Printf("Find successfully, (%d, %d) \n", p1, p2)
} else {
fmt.Printf("Not found. \n")
}
}
func main() {
FindTwoSumNumsHelper([]int {2, 7, 11, 15}, 4, 9)
FindTwoSumNumsHelper([]int {2, 2, 11, 15}, 4, 4)
FindTwoSumNumsHelper([]int {2, 9, 11, 15}, 4, -1)
}
运行结果为:
Find successfully, (1, 0)
Not found.
Not found.