Skip to content

Instantly share code, notes, and snippets.

@johnwesonga
Created May 27, 2014 11:58
Show Gist options
  • Save johnwesonga/0004dfafa522de85eee2 to your computer and use it in GitHub Desktop.
Save johnwesonga/0004dfafa522de85eee2 to your computer and use it in GitHub Desktop.
Remove duplicate values from a slice
package main
import "fmt"
//O(n^2) time
func RemoveDuplicates(data []string) []string {
length := len(data) - 1
for i := 0; i < length; i++ {
for j := i + 1; j <= length; j++ {
if data[i] == data[j] {
data[j] = data[length]
data = data[0:length]
length--
j--
}
}
}
return data
}
//O(n)
func ClearDuplicates(s []string) []string {
found := make(map[string]bool)
r := []string{}
for _, v := range s {
if _, ok := found[v]; !ok {
r = append(r, v)
found[v] = true
}
}
return r
}
func main() {
s := []string{"a", "john", "z", "b", "peter", "p", "a", "king", "k", "l", "k"}
fmt.Println(ClearDuplicates(s))
fmt.Println(RemoveDuplicates(s))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment