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 关注
- 137 浏览
添加回答
举报