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] 之間的任何引用。
- 1 回答
- 0 關注
- 159 瀏覽
添加回答
舉報