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]
要求:
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]
相关文章推荐
- LeetCode - Two Sum 完整代码(python)
- leetcode[60]Permutation Sequence 以及 全排列的编码与解码——康托展开 (附完整代码)
- GO语言发送json串数组完整代码
- Leetcode代码学习周记——Two Sum
- Mina 2 编码解码协议 及 已经实现通信的完整代码
- [LeetCode] Two Sum
- leetcode上reverse integer的C语言代码
- 网页打印完整代码
- 1_Two Sum --LeetCode
- 【个人项目】数独项目完整代码
- Echarts2绘制动态曲线图并给出完整代码
- 映射集合属性 List Hibernate 自动生成表 不需sql(附完整代码)
- 使用secondary sort实现数据关联 完整示例代码
- 编写地道的Go代码
- [Java代码] [Leetcode] Combination Sum 组合数之和
- LeetCode:Two Sum
- leetcode-1 two sum
- Leetcode代码学习周记——Longest Substring Without Repeating Characters
- 代码查看完整崩溃日志
- 基于opencv车牌识别项目完整代码