go数组中两数相加等于某个数
点击查看代码
package main
import (
"fmt"
"math/rand"
"time"
)
func sumArray(a [10]int) int {
var sum int = 0
for i := 0; i < len(a); i++ {
sum = sum + a[i]
}
fmt.Println(sum)
return sum
// for _,val ;=range a{
// sum=sum+val
// }
}
func testArraySum() {
// 产生随机化的种子
rand.Seed(time.Now().Unix())
var b [10]int
for i := 0; i < len(b); i++ {
b[i] = rand.Intn(100) // 产生0到100的随机数
}
fmt.Printf("b=%v\n", b)
sum := sumArray(b)
fmt.Printf("sum=%d\n", sum)
}
func twoSum(a [5]int, target int) {
for i := 0; i < len(a); i++ {
other := target - a[i]
for j := i + 1; j < len(a); j++ {
if a[j] == other {
fmt.Printf("%d,%d\n", i, j)
}
}
}
}
func testTwoSum() {
// var b [5]int = [5]int{1, 3, 5, 8, 7, 4} // 只能少不能多array index 5 out of bounds [0:5]
var b [5]int = [5]int{1, 3, 5, 8, 7} //
// b := [5]int{1,3,5,8,7}
// b := [...]int{1, 3, 5, 8, 7, 9}
fmt.Printf("这是b:%v\n", b)
twoSum(b, 8)
}
func main() {
// testArraySum()
testTwoSum()
}
写入自己的博客中才能记得长久