您的位置:首页 > 编程语言

LeetCode - Two Sum 完整代码(GO)

2017-09-14 16:28 399 查看
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 main

import(
"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 8
please input the target:
51
the data match the target
[1 2]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: