Created
October 19, 2017 18:29
-
-
Save karrick/6584a7b663b65db8b6ff8ac8caa2ce1e to your computer and use it in GitHub Desktop.
sortAndMaybeInsertString
This file contains 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
package sortAndMaybeInsertString | |
func sortAndMaybeInsertString(s string, a []string) []string { | |
if len(a) == 0 { | |
return append(a, s) | |
} | |
sort.Strings(a) | |
i := sort.SearchStrings(a, s) | |
if i < len(a) && a[i] == s { | |
return a // return slice when string already present | |
} | |
// Without two copies and mandatory allocation, insert string into array at | |
// index. | |
a = append(a, a[len(a)-1]) | |
copy(a[i+1:], a[i:len(a)-1]) | |
a[i] = s | |
return a | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment