3 回答

TA贡献1862条经验 获得超7个赞
func removeAdjacentDuplicate 将切片“就好像”它是对 tempData 的引用一样
main() 中 tempData 的容量和长度在程序的生命周期内保持不变
在 removeAdjacentDuplicate func 中,每次找到一个 dupe 时,“ghi”的最终值就会从末尾移动到末尾 - 1。因此,在切片末尾的记忆中,有重复的“ghi”
当控件返回到 main 时,程序将打印出现在已修改的切片 tempData。因为它是以类似于对函数的引用的方式传递的,所以修改的是此内存。函数调用未创建内存的副本
您可以通过在程序运行时查看 cap() 和 len() 来查看此行为
package main
import (
"fmt"
)
func main() {
tempData := []string{"abc", "abc", "abc", "def", "def", "ghi"}
removeAdjacentDuplicates(tempData)
fmt.Println(tempData,cap(tempData),len(tempData))
}
func removeAdjacentDuplicates(data []string) {
for j := 1; j < len(data); {
if data[j-1] == data[j] {
data = append(data[:j], data[j+1:]...)
fmt.Println(data,cap(data),len(data))
} else {
j++
}
}
fmt.Println(data, cap(data),len(data))
}

TA贡献1777条经验 获得超3个赞
在代码中,想要改变在参数中传递的 slcie。这实际上是不可能的。removeAdjacentDuplicates
此函数应返回新切片,就像返回一样。append
func removeAdjacentDuplicates(data []string) []string{
for j := 1; j < len(data); {
if data[j-1] == data[j] {
data = append(data[:j], data[j+1:]...)
} else {
j++
}
}
return data
}
如果您确实想改变参数,这是可能的,但您需要传递指向切片的指针*[]string

TA贡献1828条经验 获得超13个赞
试试这个功能:
func deleteAdjacentDuplicate(slice []string) []string {
for i := 1; i < len(slice); i++ {
if slice[i-1] == slice[i] {
copy(slice[i:], slice[i+1:]) //copy [4] where there is [3, 4] => [4, 4]
slice = slice[:len(slice)-1] //removes last element
i-- //avoid advancing counter
}
}
return slice
}
- 3 回答
- 0 关注
- 99 浏览
添加回答
举报