Last active
November 8, 2024 14:43
-
-
Save uhthomas/1577ba4809888475703101f6cb9061f4 to your computer and use it in GitHub Desktop.
deduplicate go slice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func DeduplicateSlice[T cmp.Ordered](in []T) []T { | |
slices.Sort(in) | |
out := in[:0] | |
for i := 0; i < len(in); i++ { | |
var n int | |
for j := i + 1; j < len(in); j++ { | |
if in[i] != in[j] { | |
break | |
} | |
n++ // maybe move to n = j - i - 1 | |
} | |
if n > 0 { | |
i += n | |
continue | |
} | |
out = append(out, in[i]) | |
} | |
return out | |
} | |
// in := []byte{2, 4, 1, 2, 3, 4, 7, 7, 8, 5, 6, 7, 8, 9, 10} | |
// want := []byte{1, 3, 5, 6, 9, 10} | |
// BenchmarkDeduplicateSlice-20 25569787 48.15 ns/op 0 B/op 0 allocs/op |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment