为了账号安全,请及时绑定邮箱和手机立即绑定

golang给一个int数组追加一个数字,数组中相邻元素的值发生变化,为什么?

golang给一个int数组追加一个数字,数组中相邻元素的值发生变化,为什么?

Go
MMMHUHU 2022-10-24 09:21:41
我正在尝试使用 Golang 解决一些动态编程问题。我写了一个函数func main() {    fmt.Println(HowSum(5, []int{1, 2, 5}))}func HowSum(targetNum int, numbers []int) []int {  retAry = make([][]int, targetNum+1)  retAry[0] = make([]int, 0)  for i := 0; i <= targetNum; i++ {    if retAry[i] != nil {      for _, num := range numbers {        if i+num <= targetNum {          fmt.Print("Before:", i, " round, num =", num, retAry, "\n")          retAry[i+num] = append(retAry[i], num)          fmt.Print("After :", i, " round, num =", num, retAry, "\n\n")        }      }    }  }  return retAry[targetNum]}部分结果如下。...Before:3 round, num =2 [[] [1] [1 1] [1 1 1] [1 1 1 1] [5]]After :3 round, num =2 [[] [1] [1 1] [1 1 1] [1 1 1 2] [1 1 1 2]]...[1 1 1 2 1]当程序将 retAry[5] 从 [5] 替换为 [1 1 1 2] 时,retAry[4] 中的数组从 [1 1 1 1] 更改为 [1 1 1 2]。发生什么事?但是,如果替换  retAry[i+num] = append(retAry[i], num)为retAry[i+num] = append([]int{num}, retAry[i]...),我可以得到正确的答案。...Before:3 round, num =2 [[] [1] [1 1] [1 1 1] [1 1 1 1] [5]]After :3 round, num =2 [[] [1] [1 1] [1 1 1] [1 1 1 1] [2 1 1 1]]...[1 1 1 1 1]谁能帮助解释我犯了什么错误?代码在这里
查看完整描述

1 回答

?
海绵宝宝撒

TA贡献1809条经验 获得超8个赞

However, if replace  retAry[i+num] = append(retAry[i], num) to retAry[i+num] = append([]int{num}, retAry[i]...) , I can get the correct answer.


解释:

retAry[i+num] = append(retAry[i], num)在 retAry[i+num] 和 retAry[i] 之间共享相同的数组。如果您修改一个切片,则其他切片也可以更改。


func main() {

    s1 := append([]int{}, 1, 2, 3) // len: 3, cap 4 []int{1, 2, 3, 0}


    // it appends 4 to 4th index and assign new slice to s2.

    // s2 is share the same array with s1

    // s1 : len: 3, cap 4 []int{1, 2, 3, 4}

    // s2 : len: 4, cap 4 []int{1, 2, 3, 4}

    s2 := append(s1, 4)


    // s3 is share the same array with s1 and s2 as well

    // when you append 4th index to s1, and assign to s3, both s1 and s2 will change as well

    // s1 : len: 3, cap 4 []int{1, 2, 3, 5}

    // s2 : len: 4, cap 4 []int{1, 2, 3, 5}

    // s3 : len: 4, cap 4 []int{1, 2, 3, 5}

    s3:= append(s1, 5)

    fmt.Println(s2, s3) // output [1 2 3 5] [1 2 3 5]

}

retAry[i+num] = append([]int{num}, retAry[i]...) 


[]int{num}您使用新数组初始化新切片,然后将 retAry[i] 中的每个元素附加到新数组。它们不再是 retAry[i+num] 和 retAry[i] 之间的任何引用。


查看完整回答
反对 回复 2022-10-24
  • 1 回答
  • 0 关注
  • 137 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信