![image.png](https://static.studygolang.com/180724/1171323aa100d799e5040d679188b835.png)
package main
import "fmt"
func twoSum(nums []int, target int) []int {
var result = [2]int {0,0}
if len(nums) < 2 {
return nil
}
for i := 0 ; i < len(nums) - 1; i++ {
for j := i + 1; j < len(nums); j++ {
if(nums[i] + nums[j] == target){
result[0] = i
result[1] = j
return result[:] //我理解的是返回之前初始化的result数组,无论数组元素多少,都可以以[:]代替
}
}
}
return nil
}
func main() {
var num = [4]int{2, 7 ,11, 15}
fmt.Println(twoSum(num[:] ,9))
}
有疑问加站长微信联系(非本文作者)