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 關注
- 121 瀏覽
添加回答
舉報