最近,优化一次数组去重的操作,虽然比较简单,但是还是记录下
ex:1
//数组去重
func RemoveRepByLoop(slc []int) []int {
result := []int{}
for i := range slc {
flag := true
for j := range result {
if slc[i] == result[j] {
flag = false
break
}
}
if flag {
result = append(result, slc[i])
}
}
return result
}
ex2:
func RemoveRepByLoop(slc []int) []int {
var exists = make(map[int]bool)
result := []int{} // 存放结果
for i := range slc {
if exists[slc[i]] {
continue
}
exists[slc[i]] = true
result = append(result, slc[i])
}
return result
}
ex2 会比ex1 少循环很多次
记录一次优化过程
最新推荐文章于 2026-01-06 21:43:53 发布

5313

被折叠的 条评论
为什么被折叠?



