两数据之和

2019-05-07  本文已影响0人  刺猬窝窝头
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.
上一篇 下一篇

猜你喜欢

热点阅读