美文网首页
两数据之和

两数据之和

作者: 刺猬窝窝头 | 来源:发表于2019-05-07 23:19 被阅读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.

相关文章

网友评论

      本文标题:两数据之和

      本文链接:https://www.haomeiwen.com/subject/yonuoqtx.html