gpt4 book ai didi

戈朗 : Insert to a sorted slice

转载 作者:IT王子 更新时间:2023-10-29 02:27:33 25 4
gpt4 key购买 nike

将元素插入已排序 slice 的最有效方法是什么?

我尝试了几件事,但最终都使用了至少 2 个附加项,据我所知,这生成了 slice 的新副本

最佳答案

下面是如何插入到已排序的字符串 slice 中:

Go Playground 完整示例链接:https://play.golang.org/p/4RkVgEpKsWq

func Insert(ss []string, s string) []string {
i := sort.SearchStrings(ss, s)
ss = append(ss, "")
copy(ss[i+1:], ss[i:])
ss[i] = s
return ss
}

关于戈朗 : Insert to a sorted slice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42746972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com