亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號