需求
在数组中找到 2 个数之和等于给定值的数字,结果返回 2 个数字在数组中的下标
go代码
package main
import "fmt"
func twoSum(source []int, target int) []int {
var resultArray []int
for start := 0; start < len(source)-1; start++ {
max := len(source) - 1
for start < max {
if source[start]+source[max] == target {
resultArray = append(resultArray, start, max)
break
} else {
max--
}
}
}
return resultArray
}
func main() {
source := []int{2, 3, 5, 7, 9}
const TARGET = 8
sum := twoSum(source, TARGET)
fmt.Printf("数组source:%d,任意两数和为target:%d的下标分别为:%d", source, TARGET, sum)
}
python代码