Go力扣 实现:70、1
持续更新
70 爬梯子
不能用递归,递归层数太多了,注意tmp
func ClimbStairs(n int) int {
if n == 1 {
return 1
} else if n == 2 {
return 2
} else {
f1 := 1
f2 := 2
for i := 3; i < n; i++ {
tmp := f1 + f2
f1 = f2
f2 = tmp
}
return f1 + f2
}


1、两数之和
①刚开始是返回值的问题:Go-missing return at end of function
报错原因:Go-missing return at end of function_weixin_30908103的博客-CSDN博客 一般意思是没有返回值,要用return
② 数组的声明形式,
A.最后返回的是int数组,当 a:=make([]int) 时会报错:invalid operation: make([]int) expects 2 or 3 arguments; found 1
此处是make的用(类型,内存,预留空间),报错需要2-3个参数,所以只要类型是不行的:go的make()的用法和参数含义_奋起的菜鸟_kk的博客-CSDN博客_go的make
要用在这里只能是 a:=make([]int,0),由于数组有自动扩充内容,所以0无所谓
B.关于数组的声明 ,自动推导类型[]内必须是整数且>0 Go语言中数组的声明与使用_sanqima的博客-CSDN博客_go 声明数组
a:=[2]int{1,2} => a = {1,2}
a:=[2]int => a = {0,0}
但是如果这样!就会自动填充0!!
综上所述,在数组定义时如果没有初始内容,最好不用自动推导类型, var a []int
题解:利用哈希表,为了避免结果重复,只能在遍历的时候生成哈希表
func twoSum(nums []int, target int) []int {
stoMap := make(map[int]int, 4)
a := make([]int, 0)
for i := 0; i < len(nums); i++ {
other := target - nums[i]
_, ok := stoMap[other]
if ok == true {
a = append(a, stoMap[other], i)
} else {
stoMap[nums[i]] = i
}
}
return a
}
88、