mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
refactoring: memory optimization for unique slice
This commit is contained in:
@@ -771,15 +771,19 @@ func UpdateAt[T any](slice []T, index int, value T) []T {
|
|||||||
// Unique remove duplicate elements in slice.
|
// Unique remove duplicate elements in slice.
|
||||||
// Play: https://go.dev/play/p/AXw0R3ZTE6a
|
// Play: https://go.dev/play/p/AXw0R3ZTE6a
|
||||||
func Unique[T comparable](slice []T) []T {
|
func Unique[T comparable](slice []T) []T {
|
||||||
result := []T{}
|
result := make([]T, 0, len(slice))
|
||||||
exists := map[T]bool{}
|
seen := make(map[T]struct{}, len(slice))
|
||||||
for _, t := range slice {
|
|
||||||
if exists[t] {
|
for i := range slice {
|
||||||
|
if _, ok := seen[slice[i]]; ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
exists[t] = true
|
|
||||||
result = append(result, t)
|
seen[slice[i]] = struct{}{}
|
||||||
|
|
||||||
|
result = append(result, slice[i])
|
||||||
}
|
}
|
||||||
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user