LeetCode

来源:互联网 发布:趣分期走淘宝套现 编辑:程序博客网 时间:2024/06/05 04:40
LeetCode - Two Sum 完整代码(GO)

要求:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

源码:

package mainimport(        "fmt")func two_sum(nums []int, target int) []int{        aa := []int{}        m := make(map[int]int)        for i:=0;i<len(nums);i++ {                bb,ok := m[nums[i]]                if ok && bb != i {                        aa = []int{m[nums[i]],i}                        return aa                }                m[target-nums[i]] = i        }        return aa}func main(){        var a []int        var b,x,y,z int = 0,0,0,0        fmt.Print("please input three digit:\n")        fmt.Scanf("%d%d%d",&x,&y,&z)        a = append(a,x,y,z)        fmt.Print("please input the target:\n")        fmt.Scanf("%d",&b)        d := two_sum(a,b)        if len(d) == 0 {                fmt.Print("the data don't match\n")        }else{                fmt.Print("the data match the target\n")                fmt.Println(d)        }}


测试方法:

先输入三个待匹配的数字,以空格隔开,再输入一个目标数字,最后得出是否有两个相加的数字匹配。

举例如下:

$ go run two_sum2.go please input three digit:12 43 8please input the target:51the data match the target[1 2]